![]() Join Up! 96819 members and counting! |
|
|||
Using Get and Post Methodology in AJAX Applications
Anthony Corbelli
GET is typically used when you simply need to retrieve data and POST is used when you want to change the state of the server (i.e. send/update data on the server). This article will discuss how we use GET and POST methodology in our Ajax applications!
In our last adventure we learned how to interface basic AJAX with PHP to return data from a server on the fly. This is all very well and good if the only thing you need, or want, is to retrieve basic string values from the server without refreshing the page. As soon as you want to do anything more complicated you will need a slightly larger toolset.
AJAX interacts with the server via typical GET or POST methods just like an HTML form submission to a server-side script. Let's jump into some basic JavaScript to see the difference.
I'll use the same "city and state" example as last time and then explain the changes in the code:
As you can see (refer to the code in the previous article), the only major change is the addition of a new function - makePOSTRequest(). The POST request differs from the GET request in a few important ways:
As of this writing there have been some small changes to other parts of the code, such as the addition of the timestamp to the query string and doGETRequest was renamed to makeGETRequest. The timestamp is added to help prevent caching of data from the server where it is not desirable, as may be the case if your code is changing data on the server. With an added timestamp you "trick" your browser into thinking you're sending a completely new request and, thus, it should not serve you the same data you recieved in your last request. doGETRequest was renamed for purely aesthetic reasons.
Notice the small additional check to see which method the request was sent by; if you are only using one method in your code you may not need this check, but it is a good programming practice to prepare for it, in case of a malformed request.
You can see how similar the two methods are, and how easy it is to send/update/recieve data from the server on the fly using AJAX. This sort of simple query will suit the majority of your programming needs as long as you don't need to send complex data to the server (such as objects).
If you need to send data that doesn't fit very well into string concatenation, such as objects created in classes on the client or data structures, then you will need to use a slightly more powerful variation on AJAX. That's where the XML portion of Asynchronous Javascript and XML (AJAX) comes in, sending an XML structure to the server and recieving an XML response.
Play around with using POST as a query method and come back soon, as we will be forming XML queries and receiving XML responses!
|