A very common task in jQuery is to take data from your form and send it to a server for processing. This is done so often that it’s a surprise that there is no built in method to this cleanly for json requests. Although jQuery does provide the .serializeArray()
method it doesn’t do quite what we want. It gives us an awkward array of data not suitable for sending along with the data
json formatted parameter in $.ajax
calls.
We need a simple method that will give us the form data in a json object. For this we will piggy back off of the jQuery .serializeArray()
method. We will iterate through the resulting array and turn it into a json data object that we can use for our ajax requests.
$.fn.serializeToJSON = function() { var fields = $(this).serializeArray(), data = {}; for (var key in fields) { data[fields[key].name] = fields[key].value; } return data; };
The flip side to this is to repopulate a form from a json data object. Again jQuery does not provide much for us to do this so we will create a short little method for ourselves.
$.fn.JSONtoForm = function(data) { return this.each(function() { var val, $el, $form = $(this).find('input, select'); for (var i = 0, ii = $form.length; i < ii; i++) { $el = $($form[i]); val = data[$el.attr('name')]; if (val) { $el.val(val) } } }); };
This little method will loop through the forms input
and select
fields and set their values if they exist as keys in the data
json object. Unlike our .serializeToJson()
method this one does not return any data so we can maintain method chaining on the form.