Jquery serializePost()

jQuery has a couple of useful functions that you should be using quite a lot. .serialize() and .serializeArray().

These useful functions will take your form and spit out something you can send off in your ajax requests.
“Awesome” you exclaim! “I’ll use it to send my post.

Not so fast!
Turns out these functions are more or less useless for post requests.
That’s where this nifty little function comes in handy. call $('form').serializePost() on your form and it will serialize your post data and return a nice little javascript object ready to send off. On the other end you can access it as if you had submitted the form normally using $_POST['myField'].

(function($) {
    $.fn.serializePost = function() {
        var data = {};
        var formData = this.serializeArray();
        for (var i = formData.length; i--;) {
            var name = formData[i].name;
            var value = formData[i].value;
            var index = name.indexOf('[]');
            if (index > -1) {
                name = name.substring(0, index);
                if (!(name in data)) {
                    data[name] = [];
                data[name] = value;
        return data;

Tags: ,

Matthew Hailwood is a Freelance web developer. He specializes in back-end development Specifically PHP5, SQL, and Code Igniter. He is no designer but he has a flair for user experience development using Jquery.

6 Comments Leave yours

  1. Where is the demonstration

  2. Excelente Plugins…..saludos

  3. Does this sort the posts in reverse? I seem to get the list of items backwards for posted array elements. Maybe I’m out to lunch…


  4. In your for loop you are counting down from a total number of form inputs. I changed your for loop to the following and could reference the inputs by array key. This way the array of posts are in the same order as the form elements instead of reversed. I needed to do this for a drag and drop reordering
    //the for loop
    for(var i=0; i<form.length; i++){


Leave a Reply

That's Me, I'm a web developer who's main focus is actually Back-end, Specifically PHP development. But every now and then I come up with something awesome for the front-end and this is where I share it!

More updates on Twitter