» » » Upload file won’t send to backend with Ajax

Upload file won’t send to backend with Ajax

posted in: Ajax | 0
Facebook
Google+
https://applerinquest.com/upload-file-wont-send-backend-ajax">
LinkedIn
Follow by Email

Sometimes you create a form by containing the file input field(such as upload image file) and other text input fields. And you want to send all form data to the backend using Ajax. But you find out the only the file input data won’t send to the backend. Why?

You may send the form data using serialize(). This is the cause that your backend won’t get the file input data via Ajax. Here is the code snippet using serialize().

$("body").on("beforeSubmit", "form#create-account-form", function () {
    var form = $(this);

    // return false if form still have some validation errors
    if (form.find(".has-error").length) 
    {
        return false;
    }

    // submit form
   $.ajax({
        url    : form.attr("action"),
        type   : "post",
        data: form.serialize(),   // The serialize() won't send the file input data.
        cache: false,
        processData: false,
        contentType: false,
        success: function (response) 
        {
            // do something when ajax is success.
        },
        error  : function () 
        {
            // do something when ajax is fail.
        }
    });
    return false;
});

 

To fix it, you will use FormData object instead. Here is the solution.

$("body").on("beforeSubmit", "form#create-account-form", function () {
    var form = $(this);

    // return false if form still have some validation errors
    if (form.find(".has-error").length) 
    {
        return false;
    }

    // submit form
   var formData = new FormData(form[0]); // if the form have the file input fields, you need to use FormData object in order to send all neccesorry data to Ajax.
    $.ajax({
        url    : form.attr("action"),
        type   : "post",
        data: formData, // send data to backend using FormData object
        cache: false,
        processData: false,
        contentType: false,
        success: function (response) 
        {
            // do something when ajax is success.
        },
        error  : function () 
        {
            // do something when ajax is fail.
        }
    });
    return false;
});

Hope this post helps to save your time. I always enjoy using Ajax in order to improve the user experience.

 

Facebook
Google+
https://applerinquest.com/upload-file-wont-send-backend-ajax">
LinkedIn
Follow by Email