Preparing and Sending a Request

Preparing and sending a web service request is probably one of the easiest aspects of Ajax. A few decisions about parameters, a couple of function calls, and you're done.

When preparing a request, the first decision to make is which HTTP verb to use with the request. When adding Ajax to a site, chances are you'll be working with existing web services, and you'll have to build your JavaScript client interface accordingly. However, if you're also modifying the web service interface, it'll be worth your time to review the HTTP methods that can be used between the client and the web service in order to maximize the efficiency and security of the application.

HTTP GET, POST, and RESTful Friends

I'm assuming you've probably worked with web applications before and are familiar with the GET and POST HTTP requests. XMLHttpRequest supports both of these, and a variety of other verbs. Many of those verbs don't make a lot of sense for Ajax applications, but there are four in particular that are well suited:

GET

Used to retrieve information from the web server, parameters attached to the URL, and the URL exposed in the request.

POST

Used to send information to the web server. Data is passed to the server via the function parameter.

DELETE

Used to send a request to delete a specific object. Data is passed to the server via the function parameter.

PUT

Used to send an update to the web server. Data is passed to the server via the function parameter.

The first two, GET and

Get Adding Ajax now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.