Convert an XHTML form to a JSON object, then use jQuery’s AJAX methods to send the data to the backend

Jan 29
2009
VN:F [1.3.1_645]
Rating: 5.0/5 (2 votes cast)

I had a project at work that almost drove me insane tonight. When it comes to Javascript, forget what you know about other languages, and get in the mode of: “all objects are hashes”.

Case Scenario:

You have a form with lots of dynamically created input fields. Instead of a normal submit button post, you want to send the data to the backend using AJAX.

Problem:

After hours of Googling, you just can’t find information on dynamically populating a JSON object. You also want a clean and simple way to grab all that form data, put it in a JSON object, and then submit it with jQuery’s wonderfully simple AJAX methods.

Example Solution:

XHTML from a dynamically generated form
I left some code out for simplicity, but just imagine it’s there. The inputs below are added dynamically, and can be infinite.

<form id="invite_users">
    <fieldset>
        <input name="users[0][name]" type="text">
        <input name="users[0][email]" type="text">
    </fieldset>
    <fieldset>
        <input name="users[1][name]" type="text">
        <input name="users[1][email]" type="text">
    </fieldset>
    <fieldset>
        <input name="users[1][name]" type="text">
        <input name="users[1][email]" type="text">
    </fieldset>

    <!-- ...etc...etc.. -->

    <a href="javascript:void(null)" id="#submit_form">Submit</a>
</form>

jQuery Goodness

Here is the sweet part. In this example, we just iterate through all the input fields dynamically, and place them in a JSON object — which is what jQuery’s ajax method uses to send the data back to the server.

$(document).ready(    function() {
    $("#submit_form").click(function() {
        var data = {}

        $("form#invite_users > fieldset > input").each(function() {
          data[$(this).attr("name")] = $(this).val();
        });

        $.post("post_form.php", data, function(returnData) {
          alert("Thank You!");
        });
    });
});

Easy enough?

But wait!  There’s an even better way.  With the above example, we don’t account for complex element types passed in the request ( ie, radio boxes, check boxes, file inputs ).  Once again, jQuery simplifies things even further with serializeArray():

    $("#submit_form").click(function() {
        var data = $("form#invite_users").serializeArray();

        $.post("post_form.php", data, function(returnData) {
            alert("Thank You!");
        });
    });

Hope this helps others out there! Leave a comment on your thoughts!

  • chriswpage
    Glad I could help :-)
  • Melony
    Enormous, humungous, tremendous thanks for these code snippets, Chris! After torturing myself trying to run javascript on xhtml for 3 hours (yeah, I code in the dark ages -- cdata tags? I had no clue...but don't laugh) I came across jquery and sailed through the validation, and now this jquery to pass it! If I wasnt so damn sleepy I'd be dancing now. Thanks again...
blog comments powered by Disqus

Visit Other Sites!

Find me on other sites...

Archives

All entries, chronologically...

Pages List

General info about this site...