Understanding AJAX
When you load a web page, your browser is making an HTTP request to the server. There may be some parameters to that request, either through the query string (variable=value pairs in the URL for GET) or in the body of the request (for POST). When the request completes, your browser takes the downloaded web page and displays it. AJAX, on the other hand, allows you to make HTTP requests and lets you decide what to do with the results. You can make GET and POST requests, and the data returned by the server will be available through standard JavaScript.
It's more likely that you'll use AJAX for discrete requests. You will often fetch each piece of data seperately - such as a list of recent items in one connection, and the data for each in many other connections. Because AJAX is asynchronous, you can have many AJAX requests pending at the same time, and handle each as they complete, instead of waiting for each request to complete before beginning the next.
Handling AJAX on the server
When you make AJAX requests, you are making fairly standard HTTP requests, either GET or POST requests. To serve AJAX requests on the server, you can simply output any standard HTML data.
However, there are other formats you may wish to consider, such as XML, plain text, or even JavaScript Object Notation (JSON). Each of these can be handled natively by JavaScript, and may save some data transfer compared to HTML.
Detecting AJAX requests is also an option. Adding a header to all AJAX requests is common practise; many JavaScript frameworks will add an X-Requested-With: XMLHttpRequest header which can then be detected by the web server and most scripting languages.
Event driven programming
It's also important to understand the concept of event driven programming. Because AJAX is asynchronous, you initiate a request and then continue - you don't wait for it to complete. You set a callback function to be executed when the request completes, and then move on to another task. When the AJAX request completes, the event is fired and your callback function will be executed. For a sample of event driven programming in JavaScript, see our JavaScript Events tutorial.
| « Introduction to AJAX | Basic AJAX » |

