fixing-upload-file-wont-send-to-backend-in-ajax
Home » BLOG » Upload file won’t send to backend with Ajax

Upload file won’t send to backend with Ajax

category:  jQuery, Web development

Story

You create a form with the file input field (such as upload image file) and other text input fields. You want to send all form data to the backend using Ajax. But you find out only file input data won’t send to the backend. What is the cause?

Serialize() is an issue

If you send the form data using serialize(), you come to the right place. The serialize() is the cause that your backend won’t get the file input data via Ajax. Below 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;
});

FormData object is a solution

To fix it, you will use FormData object instead. Below is the new code snippet.

$("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;
});

That’s is. Hope this post helps to save your time. Have a good day.