What‘s AJAX?
Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files. Ajax‘s most appealing characteristic, however, is its "asynchronous" nature, which means it can do all of this without having to refresh the page. This lets you update portions of a page based upon user events.
The two features in question are that you can:
Make requests to the server without reloading the page
Receive and work with data from the server
Step 1 – How to make an HTTP request
In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides this functionality. This is where XMLHttpRequest comes in.
// Old compatibility code, no longer needed. if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 6 and older httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
Next, you need to decide what you want to do after you recive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function will handle processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function that should be called when the state of the request changes.
httpRequest.onreadystatechange = nameOfTheFunction;
Note that there are no parentheses after the function name and no parameters passed, because you‘re simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous functions") and define the actions that will process the response right away, like this:
httpRequest.onreadystatechange = function(){ // process the server response };
Next, after you‘ve declared what will happen as soon as you receive the response, you need to actually make the request. You need to call the open() and send() methods of the HTTP request class, like this:
httpRequest.open(‘GET‘, ‘http://www.example.org/some.file‘, true); httpRequest.send(null);
Note that if you want to POST
data, you may have to set the MIME type of the request. For example, use the following line before calling send()
for form data sent as a query string:
httpRequest.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);1