Making a Request
23
ajax.open('GET', 'http://www.example.com/page.php', true);
ajax.send(null);
With the Ajax object created and the response handling function identified, it’s time to perform the actual request. To make an
Ajax request, you first call the open() method of the object, providing the type of request to make as the first argument, the URL
of the server resource as the second, and the value true as the third.
The most common request types are GET and POST. GET requests are the standard method for requesting any HTML page; it’s the
type of request a browser makes when you click on a link. Philosophically, GET requests are best used to fetch data. POST
requests are the standard method for form submissions (aside from search engine forms, which normally use GET).
Philosophically, POST requests are intended to cause a server change or reaction. Put another way, GET is for requests that should
be common and repeatable, even bookmarkable; POST is for unique requests, not intended to be repeated, such as the updating
of a specific database record or the submission of a contact form (in either case, the general concept will be repeated, but the
specifics would differ). Note that the method type should be in all capital letters.
The URL can be either absolute or relative , but must be accurate.
The third argument to the open() method indicates whether the request should be made asynchronously or synchronously. The
default is true, which correlates to asynchronously, but you should explicitly provide it anyway. During asynchronous requests,
other JavaScript code can be executed, such as that handling other events, while the JavaScript awaits the server response. In very
rare circumstances you will want to perform a synchronous request, as doing so prevents JavaScript from doing anything else
while the request is being made and processed, including handling user-based events (you’ll see one practical example of a
synchronous request in this chapter). If you were to perform a synchronous request, you wouldn’t create a function to handle
readyState changes, as the script waits for the server response before doing anything else anyway.
The open() method takes optional fourth and fifth arguments, representing a username and password, respectively. Both would be
necessary if the resource is protected by HTTP authentication. However, to use these arguments, you’d need access to those
values in your JavaScript code. The only secure way to do that would be to have the user input those values so they are not
hardcoded in the page’s source.
The final step is to actually send the request, by calling the send() method.