I’ve been a big fan of the YAHOO! User Interface Javascript library for some time now. It provides so many richly featured widgets and it has really forced me to learn how to write better Javascript code. That’s why I was excited by the latest release of the version 2 branch of YUI : 2.8. One new feature in YUI 2.8 that I nearly missed is form serialization. It’s a feature that I’ve been wanting for a long time and it’s a reason I’ll turn to jQuery for its serialize function.
If you’ve ever needed to post data from a form using Ajax/XHR without a serialization helper you’ve probably written code something like this:
var theForm = document.getElementById('your-form-id'); var url = theForm.action; var data = ""; data += "field1="+encodeURIComponent(theForm.field1.value)+"&"; data += "field2="+encodeURIComponent(theForm.field2.value)+"&"; data += "field3="+encodeURIComponent(theForm.field3.value); /* do ajax call */
It’s pretty tedious to write this stuff. You can write your own function to do this sort of thing but it turns out that it’s not very easy. Different input types’ values are accessed in different ways and it can get pretty ugly trying to account for them all, especially when supporting file uploads. With YUI 2.8 form serialization is part of the Connection Manager module. Here’s an example usage:
YAHOO.util.Connect.setForm('your-form-id'); YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
YUI automatically serializes the form’s data and sends it with the post request. Read more about the this new feature in the official documentation.





