[javascript] Send FormData and String Data Together Through JQuery AJAX?

How can I post file and input string data with FormData()? For instance, I have many other hidden input data that I need them to be sent to the server,

html,

<form action="image.php" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="" />
<input type="hidden" name="page_id" value="<?php echo $page_id;?>"/>
<input type="hidden" name="category_id" value="<?php echo $item_category->category_id;?>"/>
<input type="hidden" name="method" value="upload"/>
<input type="hidden" name="required[category_id]" value="Category ID"/>
</form>

With this code below I only manage to send the file data but not the hidden input data.

jquery,

// HTML5 form data object.
var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); // page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

server.php

print_r($_FILES);
print_r($_POST);

result,

Array
(
    [file] => Array
        (
            [name] => xxx.doc
            [type] => application/msword
            [tmp_name] => C:\wamp\tmp\php7C24.tmp
            [error] => 0
            [size] => 11776
        )

)

I would like to get this as my result though,

Array
(
    [file] => Array
        (
            [name] => xxx.doc
            [type] => application/msword
            [tmp_name] => C:\wamp\tmp\php7C24.tmp
            [error] => 0
            [size] => 11776
        )

)

Array
(
    [page_id] => 1000
    [category_id] => 12
    [method] => upload
    ...
)

Is it possible?

This question is related to javascript php jquery ajax form-data

The answer is


var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
    fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
    fd.append(input.name,input.value);
});
$.ajax({
    url: 'test.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});

Added a for loop and changed .serialize() to .serializeArray() for object reference in a .each() to append to the FormData.


I found that, if somehow(like your ModelState is false on server.) and page post again to server then it was taking old value to the server. So i found that solution for that.

   var data = new FormData();
   $.each($form.serializeArray(), function (key, input) {
        if (data.has(input.name)) {
            data.set(input.name, input.value);
        } else {
            data.append(input.name, input.value);
        }
    });

You can try this:

var fd = new FormData();
var data = [];           //<---------------declare array here
var file_data = object.get(0).files[i];
var other_data = $('form').serialize();

data.push(file_data);  //<----------------push the data here
data.push(other_data); //<----------------and this data too

fd.append("file", data);  //<---------then append this data

I try to contribute my code collaboration with my friend . modification from this forum.

$('#upload').on('click', function() {
            var fd = new FormData();
              var c=0;
              var file_data,arr;
              $('input[type="file"]').each(function(){
                  file_data = $('input[type="file"]')[c].files; // get multiple files from input file
                  console.log(file_data);
               for(var i = 0;i<file_data.length;i++){
                   fd.append('arr[]', file_data[i]); // we can put more than 1 image file
               }
              c++;
           }); 

               $.ajax({
                   url: 'test.php',
                   data: fd,
                   contentType: false,
                   processData: false,
                   type: 'POST',
                   success: function(data){
                       console.log(data);
                   }
               });
           });

this my html file

<form name="form" id="form" method="post" enctype="multipart/form-data">
<input type="file" name="file[]"multiple>
<input type="button" name="submit" value="upload" id="upload">

this php code file

<?php 
$count = count($_FILES['arr']['name']); // arr from fd.append('arr[]')
var_dump($count);
echo $count;
var_dump($_FILES['arr']);

if ( $count == 0 ) {
   echo 'Error: ' . $_FILES['arr']['error'][0] . '<br>';
}
else {
    $i = 0;
    for ($i = 0; $i < $count; $i++) { 
        move_uploaded_file($_FILES['arr']['tmp_name'][$i], 'uploads/' . $_FILES['arr']['name'][$i]);
    }

}
?>

I hope people with same problem , can fast solve this problem. i got headache because multiple upload image.


well, as an easier alternative and shorter, you could do this too!!

var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php?'+ other_data,  //<== just add it to the end of url ***
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

For multiple files in ajax try this

        var url = "your_url";
        var data = $('#form').serialize();
        var form_data = new FormData(); 
        //get the length of file inputs   
        var length = $('input[type="file"]').length; 

        for(var i = 0;i<length;i++){
           file_data = $('input[type="file"]')[i].files;

            form_data.append("file_"+i, file_data[0]);
        }

            // for other data
            form_data.append("data",data);


        $.ajax({
                url: url,
                type: "POST",
                data: form_data,
                cache: false,
                contentType: false, //important
                processData: false, //important
                success: function (data) {
                  //do something
                }
        })

In php

        parse_str($_POST['data'], $_POST); 
        for($i=0;$i<count($_FILES);$i++){
              if(isset($_FILES['file_'.$i])){
                   $file = $_FILES['file_'.$i];
                   $file_name = $file['name'];
                   $file_type = $file ['type'];
                   $file_size = $file ['size'];
                   $file_path = $file ['tmp_name'];
              }
        }

 var fd = new FormData();
    //Get Form Values
    var other_data = $('#form1').serializeArray();
    $.each(other_data, function (key, input) {
     fd.append(input.name, input.value);
     });

     //Get File Value
      var $file = jq("#photoUpload").get(0);
      if ($file.files.length > 0) {
      for (var i = 0; i < $file.files.length; i++) {
      fd.append('Photograph' + i, $file.files[i]);
       }
     }
$.ajax({
    url: 'test.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});

I always use this.It send form data using ajax

$(document).on("submit", "form", function(event)
{
    event.preventDefault();

    var url=$(this).attr("action");
    $.ajax({
        url: url,
        type: 'POST',            
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        }
    });
});

From what I understand you would like to send the images and the values of the inputs together. This code works well for me, I hope it helps someone in the future.

<form id="my-form" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="" />
<input type="hidden" name="page_id" value="<?php echo $page_id;?>"/>
<input type="hidden" name="category_id" value="<?php echo $item_category->category_id;?>"/>
<input type="hidden" name="method" value="upload"/>
<input type="hidden" name="required[category_id]" value="Category ID"/>
</form>

-

jQuery.ajax({
url: 'post.php',
data: new FormData($('#my-form')[0]),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
    console.log(data);
}});

Take a look at my short code for ajax multiple upload with preview.

https://santanamic.github.io/ajax-multiple-upload/


For Multiple file input : Try this code :

 <form name="form" id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]">
    <input type="file" name="file[]" >
    <input type="text" name="name" id="name">
    <input type="text" name="name1" id="name1">
    <input type="button" name="submit" value="upload" id="upload">
 </form>


 $('#upload').on('click', function() {
  var fd = new FormData();
    var c=0;
    var file_data;
    $('input[type="file"]').each(function(){
        file_data = $('input[type="file"]')[c].files; // for multiple files

     for(var i = 0;i<file_data.length;i++){
         fd.append("file_"+c, file_data[i]);
     }
    c++;
 }); 
     var other_data = $('form').serializeArray();
     $.each(other_data,function(key,input){
         fd.append(input.name,input.value);
     });
     $.ajax({
         url: 'work.php',
         data: fd,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function(data){
             console.log(data);
         }
     });
 });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to form-data

How to convert FormData (HTML5 object) to JSON Send FormData with other field in AngularJS Convert JS Object to form data Send FormData and String Data Together Through JQuery AJAX? How to add header data in XMLHttpRequest when using formdata? Node.js: How to send headers with form data using request module? How to inspect FormData? appending array to FormData and send via AJAX FormData.append("key", "value") is not working How to give a Blob uploaded as FormData a file name?