Turning a form element into JSON and submiting it via jQuery

Continuing on with our work on creating a To Do Application, this weeks snippet is on how to submit a form using jQuery. This snippet expands on what was covered in the previous tutorial, so if you’ve just joined us you might want to read it first.

JSON – JavaScript Object Notation

Last week we saw how to intercept the submit event of a form, this week we’re going to complete that method and use jQuery to perform the submit for us. There are several ways to send data back, we’re going to focus on JSON. JSON stands for JavaScript Object Notation, it is a method of specifying structured data. As it’s name suggests, it mirrors the normal JavaScript object notation.

{
    key1: 'value1',
    key2: 'value2'
}

It can also be nested to create more complex structures

{
    key1: 'value1',
    key2: 'value2',
    parent1: {
        child1: 'value of child1',
        child2: 'value of child2',
        grandchildren: {
            grandchild1: 'value of grandchild1',
            grandchild2: 'value of grandchild2',
        }
    }
}

Creating our JSON data

jQuery provides a very simple method that helps us create our JSON data object. This method is the serializeArray. To use it, all we are going to create a new JavaScript method and pass in our form reference

function ConvertFormToJSON(form){
}

To this new method we’re going to add the following

function ConvertFormToJSON(form){
    var array = jQuery(form).serializeArray();
}

We now have a JavaScript array containing each of the form elements, now all we have to do is iterate through the array items and create our JSON object

function ConvertFormToJSON(form){
    var array = jQuery(form).serializeArray();
    var json = {};
    
    jQuery.each(array, function() {
        json[this.name] = this.value || '';
    });
    
    return json;
}

This will generate a JavaScript object that looks like this:

json = {
    new-task-color: "#000000",
    new-task-date: "25/04/2013T08:00:00",
    new-task-desc: "Creating a simple to-do application tutorial on developerdrive.com",
    new-task-email: "you@everyone.com",
    new-task-name: "Create a simple to-do application",
    new-task-priority: "2"
}

Now using the jQuery Ajax method we will submit the data to our (non-existent) submit.php file.

jQuery(document).on('ready', function() {
    jQuery('form#add-new-task').bind('submit', function(event){
        event.preventDefault();

        var form = this;
        var json = ConvertFormToJSON(form);

        $.ajax({
            type: "POST",
            url: "submit.php",
            data: json,
            dataType: "json"
        });
		
        var tbody = jQuery('#to-do-list > tbody');
        
        tbody.append('<tr><th scope="row" style="background-color:' + this['new-task-color'].value + 
            '"><input type="checkbox" /></th><td>' + this['new-task-date'].value +
            '</td><td>' + this['new-task-priority'].value + '</td><td>' + this['new-task-name'].value + 
            '</td><td>' + this['new-task-desc'].value + '</td><td>' + this['new-task-email'].value + '</td></tr>');                
        
        return true;
    });
});

We only want to update the table if the submit is a success, so we’re going chain another 2 functions on to our AJAX method for success and failure events.

jQuery(document).on('ready', function() {
    jQuery('form#add-new-task').bind('submit', function(event){
        event.preventDefault();
        
        var form = this;
        var json = ConvertFormToJSON(form);
        var tbody = jQuery('#to-do-list > tbody');

        $.ajax({
            type: "POST",
            url: "submit.php",
            data: json,
            dataType: "json"
        }).done(function() { 
            tbody.append('<tr><th scope="row" style="background-color:' + form['new-task-color'].value + 
                '"><input type="checkbox" /></th><td>' + form['new-task-date'].value +
                '</td><td>' + form['new-task-priority'].value + '</td><td>' + form['new-task-name'].value + 
                '</td><td>' + form['new-task-desc'].value + '</td><td>' + form['new-task-email'].value + '</td></tr>');    
        }).fail(function() { 
            alert("Failed to add to-do"); 
        });

        return true;
    });
});

To test this you can either create a sample submit.php file or instead of the done method, you can use ‘always’. The attached demo and download files are configured to use this method.

Summary

There you have it a quick and easy way of turning a form in to a JSON object and submitting it using AJAX. Next week, we’ll be creating our submit.php and creating our initial MySql database.

A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio More articles by Jonathan Schnittger
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress