Serialize a form with jQuery to perform an ajax post

Here is the proper way to a serialize a form with jQuery.

To do that you’ll have to use serializeArray() function of jQuery which returns a formular data in this form [ { name : “name”, value : value}, …} ]

The problem with it is that it doesn’t integrate the submit button in the data (sometimes we use it in the back-end) and it is not possible to give this array as an argument for the jQuery.post function because it requires an associative array {name:value, name:value}
Also, when there is multiple select or radio buttons, not all selected values all sent but only one. The reason why is that they have the same names so the result of form.serializeArray() would be for this form :

<form id="myform">
    <select multiple name="countries">
        <option value=1>USA</option>
        <option selected value=2>France</option>
        <option selected value=3>Canada</option>
    </select>
</form>
$("#myfrom").serializeArray() :
[
    {name:"countries", value="2"}, // France
    {name:"countries", value="3"}, // Canada
]

// IF we convert it to the format accepted by $.post, we could have :
{"countries":3} // last one selected only

The proper method is :

function postForm(form, callback) {
    var url = form.attr('action');
    var postData = form.serializeArray(); // serializes the form data to an array
    var submit_button = form.find("input[type='submit']");
    if(submit_button.length) {
        // Add the submit button to the post data
        postData.push({name:submit_button.attr("name"), value:submit_button.attr("value")});
    }

    // Then we're going to convert the postData to a format accepted by jQuery.post
    var postParams = []; // postParams that we'll give to jQuery.post
    for(var i in postData) {
        if(postParams[postData[i].name]) { // Already exists
            if(!Array.isArray(postParams[postData[i].name])) {
                postParams[postData[i].name] = [postParams[postData[i].name]];
            }

            postParams[postData[i].name].push( postData[i].value);
        } else {
            postParams[postData[i].name] = postData[i].value;
        }
    }

    // Finally, post the form and call the callback function
    jQuery.post(url, postParams, function(data) {
        callback(data);
    });
}

Leave a Reply

Your email address will not be published. Required fields are marked *