Home >Backend Development >PHP Tutorial >How to Transmit Both FormData and String Data in a JQuery AJAX Request?
When working with forms that contain both file inputs and hidden input fields, you may encounter difficulties sending both sets of data together using FormData(). This article provides a solution to this problem.
In FormData, you can append file data using the method fd.append("file", file_data). However, to include hidden input data along with the file, you'll need to use the following steps:
For example, consider the HTML code:
<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>
And the following JQuery/Ajax code:
<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>
This code first obtains the files from the input and appends them to the FormData object. It then obtains the values from the hidden input fields using serializeArray() and appends them to the FormData object as well. Finally, the data is sent to the server using an Ajax request.
By following these steps, you can successfully send both FormData and string data together through JQuery AJAX, ensuring that all necessary data is transmitted with the request.
The above is the detailed content of How to Transmit Both FormData and String Data in a JQuery AJAX Request?. For more information, please follow other related articles on the PHP Chinese website!