Jquery Ajax FormData not passing File Object

Solution:1

Your Ajax Request should be like this

$.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: data,
        dataType: "JSON",
        contentType: false,    //Required
        cache: false,          //Required
        processData: false,    //Required
        beforeSend: function () {
            //Your functions before send AJAX Request
        },
        success: function (feedback) {
            //Your functions after AJAX Request Success
        },
        error: function (error) {
            console.log(error);
        },
    });   

And You can get all the form data using

var data = new FormData(document.getElementById("yourFromId"));

Solution:2

When you’re sending an ajax request via jQuery and you want to send FormData you don’t need to use JSON.stringify on this FormData. Also when you’re sending file the content type must be multipart/form-data including boundry – something like this multipart/form-data; boundary=----WebKitFormBoundary0BPm0koKA

So to send FormData including some file via jQuery ajax you need to:

  • Set data to the FormData without any modifications.
  • Set processData to false (Lets you prevent jQuery from automatically transforming the data into a query string).
  • Set the contentType to false (This is needed because otherwise jQuery will set it incorrectly).

Your request should look like this:

var formData = new FormData();

formData.append('name', dogName);
// ... 
formData.append('file', document.getElementById("dogImg").files[0]);


$.ajax({
    type: "POST",
    url: "/foodoo/index.php?method=insertNewDog",
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
        console.log(response);
    },
    error: function(errResponse) {
        console.log(errResponse);
    }
});