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!
Comment