Home >Backend Development >PHP Tutorial >How to Submit a File Upload Form Using jQuery Ajax?
You have a form that you're submitting through Ajax using the jQuery serialization function. However, you're encountering issues when the form includes an field. The serialized form data doesn't include the file, and printing $_FILES results in an empty result.
To resolve this issue, you can utilize the FormData object. It is compatible with any form type, including those with file inputs. Here's how to implement it:
$(document).on("submit", "form", function(event) { event.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), dataType: "JSON", data: new FormData(this), processData: false, contentType: false, success: function (data, status) { }, error: function (xhr, desc, err) { } }); });
By using the FormData object, you can pass the file along with other form data in the Ajax request. The processData and contentType options are set to false to prevent jQuery from handling data and content-type and allow the browser to handle form submission correctly.
The above is the detailed content of How to Submit a File Upload Form Using jQuery Ajax?. For more information, please follow other related articles on the PHP Chinese website!