Search code examples
javascriptjqueryajaxmultipartform-dataform-data

Using FormData object in jQuery ajax request makes page redirect


I have been using the following piece of jQuery ajax in my website to submit form data to the server without redirecting the page.

$(document).ready(() => {
    const form = $("#submitableform");
    form.submit((event) => {
        event.preventDefault();
        $.ajax({
            type: $(form).attr('method'),
            url: $(form).attr('action'),
            dataType : 'json',
            data: $(form).serialize(),
            success: (result) => formSuccessFunction(result),
            error: (xhr, resp, text) => {
                console.log(xhr, resp, text);
            }
        });
    });
});

Everything has been working fine. I can submit the form, the page doesn't redirect and I can view all my data in the server app and the json response is sent back the client.

I now want to upload a thumbnail image with this form data. I found that I can use the FormData object to submit a multipart-formdata. This seemed to be what I might want.

I updated my jQuery call to the following:

$(document).ready(() => {
    const form = $("#submitableform");
    form.onsubmit((event) => {
        let formData = new FormData(this);
        event.preventDefault();
        $.ajax({
            type: $(form).attr('method'),
            url: $(form).attr('action'),
            processData: false,
            contentType: false,
            data: formData,
            success: (result) => formSuccessFunction(result),
            error: (xhr, resp, text) => {
                console.log(xhr, resp, text);
            }
        });
    });
});

The form data still find its way to the server but now the page redirects to the page in the url. I cannot figure out why at all.

Also regarding the file I want to upload - only the filename is uploaded. Is this right? It's years since I have done it and I can't remember that one :)

Does anybody have any clues as to why this small change now makes my ajax request.....not an ajax request.

Thanks in advance.

(PS I have not shown my html as this has not changed at all and the original request worked. All the input field and form ids etc are exactly the same.)


Solution

  • The form data still find its way to the server but now the page redirects to the page in the url. I cannot figure out why at all.

    In the first handler you are using:

    form.submit((event) => {
    

    This is the .submit() method to handle the

    .on( "submit", handler )

    In your second fragment, instead you are using:

    form.onsubmit((event) => {
    

    The onsubmit is not a jQuery method hence your problem.

    A second issue is related to this line:

    let formData = new FormData(this);
    

    Change it to:

    let formData = new FormData(event.target);
    

    The this keyword in your function context is not the current form but the default window object.