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:
// Create a new FormData object
var fd = new FormData();
// Append file data
for (var i = 0; i Submitting the Data Using AJAX:
$.ajax({
url: 'submit.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log(data);
},
});
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:
// Files
print_r($_FILES);
// Other data
print_r($_POST);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3