Home >Backend Development >PHP Tutorial >How to Send FormData and String Data Simultaneously in JQuery AJAX?
Sending FormData and String Data Simultaneously in JQuery AJAX
When working with forms involving file uploads, it is necessary to combine file data with additional string data for submission to the server. Here's how to achieve this using FormData() in JQuery AJAX:
Building the FormData with File and String Data:
<code class="javascript">// Create a new FormData object var fd = new FormData(); // Append file data for (var i = 0; i < file_data.length; i++) { fd.append("file_" + i, file_data[i]); } // Append other string data using serializeArray() var other_data = $('form').serializeArray(); $.each(other_data, function (key, input) { fd.append(input.name, input.value); });</code>
Submitting the Data Using AJAX:
<code class="javascript">$.ajax({ url: 'submit.php', data: fd, contentType: false, processData: false, type: 'POST', success: function (data) { console.log(data); }, });</code>
Explanation:
Server-Side Considerations:
To retrieve the file and string data on the server, you can use the following code:
<code class="php">// Files print_r($_FILES); // Other data print_r($_POST);</code>
The above is the detailed content of How to Send FormData and String Data Simultaneously in JQuery AJAX?. For more information, please follow other related articles on the PHP Chinese website!