The XMLHttpRequest object is used to exchange data with a server.
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
|open(method,url,async)||Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
|send(string)||Sends the request off to the server.
string: Only used for POST requests
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A simple GET request:
In the example above, you may get a cached result.
To avoid this, add a unique ID to the URL:
If you want to send information with the GET method, add the information to the URL:
A simple POST request:
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:
|setRequestHeader(header,value)||Adds HTTP headers to the request.
header: specifies the header name
value: specifies the header value
The url parameter of the open() method, is an address to a file on a server:
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can perform actions on the server before sending the response back).
Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.
When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:
You will learn more about onreadystatechange in a later chapter.
To use async=false, change the third parameter in the open() method to false:
Using async=false is not recommended, but for a few small requests this can be ok.
Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the send() statement: