AJAX - The Complete Reference

(avery) #1

126 Part I: Core Ideas


Form Serialization


We know from previous sections that when browsers send form data to the server, the
various name-value pairs are encoded and separated by ampersands. This process is called
serialization and is performed automatically for us. Given that in an Ajax application, the
form data is often prepared for submission by the programmer, it is useful to have a
function do this for you. To make our own serialization mechanism, we must note a few
other details in how form data is sent. First, note that fields with no values may not be sent.
Second, disabled fields are not sent. Finally, according to specification, fields should be sent
in the order in which they appear in the document. We present a serialization function that
does all this plus the standard name-value pair composing here:

function serializeForm(form, encoding, trigger, evt)
{
var formValues = null;
var x=0,y=0;
if (trigger && trigger.type == "image" && trigger.name)
{
if (window.event)
{
x = window.event.offsetX;
y = window.event.offsetY;
}
else if (evt.target)
{
var coords = {x: 0, y: 0 };
var elmt = trigger;
while (elmt)
{
coords.x += elmt.offsetLeft;
coords.y += elmt.offsetTop;
elmt = elmt.offsetParent;
}
x = evt.clientX + window.scrollX - coords.x - 1;
y = evt.clientY + window.scrollY - coords.y - 1;
}
}

for (var i =0; i < form.elements.length; i++)
{
var currentField = form.elements[i];
var fieldName = currentField.name;
var fieldType = currentField.type;
/* Disabled and unnamed fields are not sent by browsers so ignore them */
if ((!currentField.disabled) && fieldName)
{
switch (fieldType)
{
case "text":
case "password":
case "hidden":
Free download pdf