What ' s AJAX?
Ajax stands for asynchronous JavaScript and XML. In a nutshell, it's 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, was its "asynchronous" nature, which means it can does all the this without HAV ing to refresh the page. This lets you update portions of a page based upon user events.
The features in question is that 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 functi Onality. This is where the 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 are you want to does after you recive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function would handle processing the response . This is do by setting the onReadyStateChange property of the object to the name of the JavaScript function that should b E called when the state of the request changes.
Httprequest.onreadystatechange = nameofthefunction;
Note that there is no parentheses after the function name and no parameters passed, because you ' re simply assigning a ref Erence 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 "an Onymous functions ") and define the actions that would process the response right away, like this:
Httprequest.onreadystatechange = function () { //Process the server response};
Next, after your ' ve declared what would 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 as this:
Httprequest.open (' GET ', ' http://www.example.org/some.file ', true); Httprequest.send (null);
Note If you POST
are want to data, the MIME type of the request. For example, with the following line before calling for send()
form data sent as a query string:
Httprequest.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded '); 1
Ajax Basics (i)