Home  >  Article  >  Backend Development  >  How to Send FormData and String Data Simultaneously Using JQuery AJAX

How to Send FormData and String Data Simultaneously Using JQuery AJAX

DDD
DDDOriginal
2024-10-22 15:16:02844browse

How to Send FormData and String Data Simultaneously Using JQuery AJAX

Sending FormData and String Data Simultaneously Through JQuery AJAX

Transmitting both file data and regular input string data through a single AJAX request can be achieved with FormData(). For instance, you may have multiple hidden input fields that you want to include in the server request alongside the file data.

Consider the following HTML form:

<code class="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></code>

Using the following JQuery code, however, only the file data is being sent, leaving out the hidden input data:

<code class="jquery">// HTML5 form data object.
var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); // page_id=&amp;category_id=15&amp;method=upload&amp;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);
    }
});</code>

The key to including both file and string data within FormData() lies in modifying the JQuery code as follows:

<code class="javascript">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);
    }
});</code>

The modifications introduced a for loop that handles multiple file inputs and changes .serialize() to .serializeArray() to obtain an array of objects for manipulation in a .each() loop, where data can be appended to FormData().

The above is the detailed content of How to Send FormData and String Data Simultaneously Using JQuery AJAX. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn