Wednesday, November 17, 2010

Just serialize me

Often when you are building a website you are offering up some type of content. Occasionally, though you need to capture some end user data and one of the tried and true methods of the world wide web is to use forms to do that. Most forms have some type of format similar to this example:

<form name="someForm" action="somePage.asp" method="post">
 <input name="someField" type="text" />
 <input name="aField" type="text" />
 <input type="submit" name="submit" />
</form>

This is just a simple form that submits two fields of text. With a simple javascript variable you can grab all form fields and by using the handy serialize method you can convert all your form data into a query string.

var someJavascriptVariable = $("#someForm").serialize();

If you prefer to use JSON or some similar type of format you an call the serializeArray method. This returns an object containing the key and value pairs of all your form data.

var someJavascriptVariable = $("#someForm").serializeArray();

You can then combine this with the $.post method to submit your data to a database.

$.post(this.someURL, someJavascriptVariable, function() { alert("submitted!"); });

I added a callback at the end that gives is a pop-up message letting us know that the form has been submitted.

No comments:

Post a Comment