Home  >  Article  >  Backend Development  >  How to Transmit Both FormData and String Data in a JQuery AJAX Request?

How to Transmit Both FormData and String Data in a JQuery AJAX Request?

DDD
DDDOriginal
2024-10-22 14:18:03368browse

How to Transmit Both FormData and String Data in a JQuery AJAX Request?

How to Send Both FormData and String Data Through JQuery AJAX?

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:

  1. Use $('form').serializeArray() to obtain an array of objects representing each input field and its value.
  2. Iterate through the array and append each field's name and value to the FormData object using fd.append(input.name,input.value).

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!

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