Home > Backend Development > PHP Tutorial > How to Submit a File Upload Form Using jQuery Ajax?

How to Submit a File Upload Form Using jQuery Ajax?

Susan Sarandon
Release: 2024-12-11 07:58:11
Original
523 people have browsed it

How to Submit a File Upload Form Using jQuery Ajax?

File Upload Using jQuery Serialization

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.

Solution: Using FormData Object

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) {
            
        }
    });        
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template