jQuery Form Serialization Plugin

For a number of projects I've needed to serialize all of the values in a form on the client to JSON in order to post the data back to the server via AJAX.

Here's a little jQuery plugin I wrote to help with this task. It finds each input element of the selected form and adds a property with the name and value of the input element to the object that is passed in.

  
(function($) {
    $.fn.formToObj = function(target) {
        // Serialize all the inputs except radio buttons and checkboxes
        this
            .find(":input")
            .not(":radio:unchecked, :checkbox")
            .filter(function() { return this.name; })
            .each(function(idx, input) {
                target[input.name] = $(this).val();
            }); 

        // Serialize the checkboxes and radio buttons
        this
            .find(":input:checkbox")
            .filter(function() { return this.name; })
            .each(function(idx, input) {
                target[input.name] = new Boolean($(input).attr("checked"));
            }); 

        return this;
    };  
})(jQuery);

This extension can be used simply with the jQuery AJAX methods. This example posts the data object back to the server as JSON in a POST variable called data and then puts the server's response into a page element with an ID of response.

  
// Serialize the form                                                                                                                                           
var data = {};  
$("form").formToObj(data);

// AJAX post the data to the server
$.post("post.php", { "data": JSON.stringify(data) }, function(rdata) {
    // Display the result from the server
    $("#response")
        .html(rdata)
        .slideDown();
});

And here's some server-side PHP code for a simple form with a single text input for someone to signup for notifications on our site. PHP json_decode will take the JSON that was posted and create a PHP object which we can access properties of the same name as the input elements on the form.

  
<?php                                                                                                                                                           
    if($_SERVER['REQUEST_METHOD'] != "POST") {
        header("Status: 405 Method Not Allowed");
        header("Allow: POST");
        return;
    }

    $data = json_decode($_POST['data']);
    mail('josh@example.com', 'site signup', "$data->email signed up for your site.", "From: josh@example.com (Josh Perry)");

    echo "Thank you for signing up to be notified!";
?>