sharif9876
sharif9876

Reputation: 680

ajax submitting forms using FormData

I was trying to submit only specific inputs of a very large form and I wanted to do this using ajax. I had this and it was working fine. This will submit all inputs within #someDiv.

$(".save").click(function () {

    dat = $.param($('#someDiv').find('input'));

    $.ajax({
        type: "POST",
        url: "...",
        data: dat,
        success: function(data) {
            //success
        }
    });
});

I then remembered that some of these inputs are file inputs so this will not work. I did some research and found that using FormData was the way to go:

$(".save").click(function () {

    dat = new FormData($('#someDiv').find('input'));

    $.ajax({
        type: "POST",
        url: "...",
        data: dat,
        processData: false,
        contentType: false,
        success: function(data) {
            //success
        }
    });
});

But this function is not working, the success function is firing but nothing is saving so I assume the FormData is not being created properly. Any ideas? Thanks in advance

Upvotes: 0

Views: 896

Answers (1)

sanjeev
sanjeev

Reputation: 4621

You can't create a formData as below

dat = new FormData($('#someDiv').find('input'));

you need to pass the Javascript form reference to the form , for example if the id of the form is , singupForm then do it like below

dat = new FormData($('#singupForm')[0]);

Edit

In case you want to add only selected field you can do it as below

    var formData = new FormData();
    formData.append("variable", "First Value");
    formData.append("integerVariable", 987654321); 

    // For file, remember to pass the JavaScript reference
    formData.append("userfile", fileInputElement.files[0]);

Upvotes: 5

Related Questions