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

How to Send FormData and String Data Simultaneously in JQuery AJAX?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 14:20:03958browse

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:

  • serializeArray(): This method retrieves the form data as an array of objects, providing better control over each input's name and value.
  • contentType: false and processData: false: These settings disable JQuery's default data processing and allow for the raw FormData to be sent to the server.
  • 'submit.php': Replace this with the URL of the server-side script that will handle the file and string data.

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!

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