Serialize and Un-Serialize Form Data

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.

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.