jQuery in Action
228
CHAPTER 8
Talk to the server with Ajax
The
serialize()
command is smart enough to only collect information from
form control elements in the wrapped set, and only from those qualifying ele-
ments that are deemed successful. A successful control is one that would be
included as part of a form submission according to the rules of the
ments that are deemed successful. A successful control is one that would be
included as part of a form submission according to the rules of the
HTML
Speci-
fication.
2
Controls such as unchecked check boxes and radio buttons, dropdowns
with no selections, and any disabled controls are not considered successful and do
not participate in the submission. They are also ignored by
not participate in the submission. They are also ignored by
serialize()
.
If we'd rather get the form data in a JavaScript array (as opposed to a query
string), jQuery provides the
serializeArray()
method.
The array returned by
serializeArray()
is composed of anonymous object
instances, each of which contains a
name
property and a
value
property that con-
tain the name and value of each successful form control.
With the
load()
command at our disposal, let's put it to work solving a com-
mon real-world problem that many web developers encounter.
Command syntax: serialize
serialize()
Creates a properly formatted and encoded query string from all successful form elements in
the wrapped set
the wrapped set
Parameters
none
Returns
The formatted query string
The formatted query string
2
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
Command syntax: serializeArray
serializeArray()
Collects the values of all successful form controls into an array of objects containing the
names and values of the controls
names and values of the controls
Parameters
none
Returns
The array of form data
The array of form data