durisvk
durisvk

Reputation: 957

FormData gets uncaught type error

I am making a form submission through AJAX using jQuery. I have the following code:

$("#myForm-form").on("submit", function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: { 
            'eoss': 'indexEOSS',
            'form': 'myForm',
            'values': createJSON(), 
            'formData': formData 
        },
        success: function(data) {
            console.log(data);
            eval(data);
            myFormForm(data);
        },
        processData: false,
        contentType: false
    }); 
    return false
});

However I get this:

GET http://localhost/EOSS2/request.php?[object%20Object] 404 (Not Found)

When I remove processData: false and contentType: false I get the following error:

Uncaught TypeError: Illegal invocation

What should I do?

Upvotes: 1

Views: 795

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

You have two issues here. Firstly your error message indicates that you're sending a GET request, which does not work with FormData. Using POST would seem the most applicable in this case.

Secondly, you cannot send FormData in an object as jQuery will attempt to URL encode it which will lead to issues. Instead use the append() method to add information to your FormData object. Try this:

$("#myForm-form").on("submit", function(e) {
    e.preventDefault();

    var $form = $(this);
    var formData = new FormData($form[0]);
    formData.append('eoss', 'indexEOSS');
    formData.append('form', 'myForm');
    formData.append('values', createJSON());

    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'), // change the attribute in HTML or hardcode to 'post'
        data: formData,
        success: function(data) {
            console.log(data);
            // eval(data); < never, ever use eval()
            myFormForm(data);
        },
        processData: false,
        contentType: false
    }); 
});

Upvotes: 2

Related Questions