AJAX - The Complete Reference

(avery) #1

128 Part I: Core Ideas


keywords for other data formats such as JSON to trigger an alternate scheme as we will
demonstrate later.

var payload = serializeForm(document.getElementById("contactForm"),"JSON");
var payload2 = serializeForm(document.getElementById("orderForm"),"default");

In some situations, it may be necessary to transmit data to the server that specifies
which button the user clicked to submit the form. This is commonplace in traditional Web
forms when there are multiple submit buttons as shown here.

<input type="submit" value="add" onclick="serializeForm(this.form,'default',
this); return false;" />
<input type="submit" value="delete" onclick="serializeForm(this.
form,'default', this); return false;" />

Finally, if image buttons are used in the page, you will need to pass an event object to
the function to calculate the coordinates of the click if the server depends upon knowing
such things.

<input type="image" value="add" border="2" src="add.gif" height="20"
width="20" name="add" onclick="serializeForm(this.form,"default",
this,event);" />
<input type="image" value="delete" border="2" src="delete.gif" height="20"
width="20" name="delete" onclick="serializeForm(this.form,"default",
this,event);" />

Unlike many form serialization routines found online, this function simulates how
browsers act nearly exactly. Most importantly, it addresses edge cases and handles image
fields properly, making sure to send the coordinates of the click on the image. However,
even trying to address all the details found in forms, there are some cases where simulating
the browser exactly is a bit difficult because various browsers act differently. For example,
in the case of <input type="image" value="imagebutton" />, the value in some
browsers, like Internet Explorer, is not sent, while in others it is. In some browsers, such as
Firefox, the position of the image field is preserved in the document flow, others like
Internet Explorer and Opera always put it at the end. In practice these issues should not
matter, but we present this detail for completeness in case you notice it during testing.

Object Serialization


Form serialization works really well when only form-entered data is being sent to the
server, but what if it is necessary to include other data that is not supplied via a form? In
this case, it is possible to serialize script-based values in the standard or in the extended
URL encoded format previously discussed. The following serializeObject() function
accomplishes this useful task:

function serializeObject(obj)
{
var payload="";
for (var key in obj)
payload += "&"+encodeValue(key) +"=" + encodeValue(obj[key]);
return payload;
}
Free download pdf