Tuesday, June 24, 2008

jQuery form plugin data manipulation

jQuery form plugin is a great piece of code, and if you are working with ajax forms its your best friend. The basic usage of it is excellently explained of their site.

It happens from time to time that you have to serialize/create some values into a hidden form field and extract the data on the server side. I came up with a solution to avoid this unnecessary serialization/deserialization.

You can provide your custom code in beforeSubmit callback. It works like this:

beforeSubmit: function(formData, jqForm, options) {
name: 'aListItems['+$(this).attr('value')+']',
value: $(this).text()

This code snippet would find a select field named 'listItems' within the posted form and convert all of its options into an array that gets posted to server side (and there easily accessible trough $_POST from PHP).

formData parameter of beforeSubmit callback is an JS array that contains all the fields of the form, and as it is passed by reference you can add your custom fields to it, and form plugin will see them as parts of the form. jqForm parameter is a reference to jQuery ajaxForm object, so you can use it to extract data.

This solution should work for any type of data manipulation before the form submit.

No comments: