Thursday, January 29, 2009

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

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 = {}

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

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


Wallah! There you have it. I found this to be very clean for my purposes, and am contemplating writing a jQuery plugin for it - though, I'm not really sure I have the time.

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