Posting Both File and String Data with FormData() and jQuery AJAX
It is often necessary to send both file and input string data through AJAX requests. To achieve this using FormData(), follow these steps:
Create a FormData Object:
<code class="js">var fd = new FormData();</code>
Append File Data:
a. For a single file:
<code class="js">fd.append("file", file_data);</code>
b. For multiple files:
<code class="js">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]); }</code>
Append String Data:
<code class="js">var other_data = $('form').serializeArray(); $.each(other_data,function(key,input){ fd.append(input.name,input.value); });</code>
Send Data with AJAX:
<code class="js">$.ajax({ url: 'url', data: fd, contentType: false, processData: false, type: 'POST', success: function(data){ alert(data); } });</code>
By following these steps, you can send both file and input string data within the same FormData object and AJAX request.
The above is the detailed content of How to Send Both File and String Data with FormData() and jQuery AJAX?. For more information, please follow other related articles on the PHP Chinese website!