(^194) ❘ CHAPTER 7 AJAX
FIGURE 7-3
You’ve added a new event to the <input> element with the id name addressButton. When you click
the <input> element, a POST request is initiated using jQuery’s $.post() method. Of course, you
have no HTTP server set up to transmit this data to, so, instead, you simply reference a static JSON
fi le that lets you know the POST request succeeded at least as far as requesting the specifi ed docu-
ment. In the second argument to the $.post() method, you supply the data that you want to trans-
mit to the server, just like you can do with the $.get() and $.getJSON() methods that you saw in the
previous two sections. However, in addition to supporting an object literal, you can also provide a
serialized string of URL-encoded key, value pairs. This is what the serialize() method provides;
it encodes key, value pairs and creates a URL-encoded string from them. It searches within the
<form> element for all <input>, <textarea>, and <select> elements automatically when you select
a <form> element. You can also tell it specifi cally which <input>, <textarea>, or <select> elements
you want to serialize by explicitly selecting those elements. That selection is then passed to jQuery’s
serialize() method, which fi nds the right names and values from the various input elements,
formatting that data like so:addressCountry=223
&addressStreet=123+Main+Street
&addressCity=Springfield
&addressState=23
&addressPostalCode=12345This data appears as one unbroken line when it is passed to serialize(); some line breaks have been
added here to make the string more readable. This data is now ready to be posted to the server, so
all you have to do is pass this formatted data in the data argument of the $.post() method. This
also works for jQuery’s other AJAX request methods as well, and jQuery is smart enough to know
when you’re passing an object literal, as I demonstrated previously, and when you’re passing a
formatted query string, like you are here. Then, on the server side, all you have to do is access the
posted data as you would normally work with POST request data.