jQuery in Action
234
CHAPTER 8
Talk to the server with Ajax
control over which
HTTP
method gets used. Why should we care? Because,
maybe, our servers care.
Web authors have traditionally played fast and loose with the
GET
and
POST
methods, using one or the other without heeding how the
HTTP
protocol intends
for these methods to be used. The intentions for each method are as follows:
GET
requests--Intended to be idempotent; the state of the server and the
model data for the application should be unaffected by a
GET
operation.
The same
GET
operation, made again and again and again, should return
exactly the same results (assuming no other force is at work changing the
server state).
server state).
POST
requests--Can be non-idempotent; the data they send to the server can
be used to change the model state of the application; for example, adding
records to a database or removing information from the server.
records to a database or removing information from the server.
A
GET
request should, therefore, be used for getting data (as its name implies). It
may be required to send some data to the server for the
GET
; for example, to iden-
tify a style number to retrieve color information. But when data is being sent to
the server in order to effect a change,
the server in order to effect a change,
POST
should be used.
WARNING
This is more than theoretical. Browsers make decisions about caching
based upon the
based upon the
HTTP
method used;
GET
requests are highly subject to
caching. Using the proper
HTTP
method ensures that you don't get
cross-ways with the browser's expectations regarding the intentions of
the requests.
the requests.
All that being said, jQuery gives us a few means to make
GET
requests, which
unlike
load()
, aren't implemented as jQuery commands for a wrapped set. Utility
functions are provided to make various types of
GET
requests. As we pointed out in
chapter 1, jQuery utility functions are top-level functions that are namespaced
with the
with the
jQuery
global name or its
$
alias.
Let's look at each of these functions.
8.3.1 Getting data with jQuery
When we want to fetch some data from the server and decide what to do with it
ourselves (rather than letting the
ourselves (rather than letting the
load()
command set it as the content of an
HTML
element), we can use the
$.get()
utility function. Its syntax is as follows: