Ad

Uncaught TypeError Illegal Invocation When Send FormData To Ajax

- 1 answer

I am trying to send a file to the server to do some processing. This is working perfectly fine using the below code:

var formData = new FormData();
formData.append('file', $('#fileUpload')[0].files[0]);
options = JSON.stringify(options); // {"key": "value"}

$.ajax({
        url: "url",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {

        },
        error: function (msg) {
            showMsg("error", msg.statusText + ". Press F12 for details");
            console.log(msg);
        }
    });

However, what I am trying to do is not only send the FormData but a json object as well. I am trying to do something like below:

var formData = new FormData();
formData.append('file', $('#fileUpload')[0].files[0]);
options = JSON.stringify(options); // {"key": "value"}

$.ajax({
        url: "url",
        type: "POST",
        data: { "formData": formData, "options": options },
        //dataType: "json",
        //processData: false,
        //contentType: false,
        success: function (data) {

        },
        error: function (msg) {
            showMsg("error", msg.statusText + ". Press F12 for details");
            console.log(msg);
        }
    });

When I do this, I get the error message of Uncaught TypeError Illegal invocation From what i've researched, I cannot find any examples of sending form data like this. Does this need to be restructured of is there some other way to send a json object along with the form data?

Ad

Answer

Appending the JSON object options to the FormData works.

var formData = new FormData();
formData.append('file', $('#fileUpload')[0].files[0]);
options = JSON.stringify(options);
formData.append('options', options); //append it with the form data and take it apart on the server

$.ajax({
    url: "url",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (data) {

    },
    error: function (msg) {
        showMsg("error", msg.statusText + ". Press F12 for details");
        console.log(msg);
    }
});
Ad
source: stackoverflow.com
Ad