Ajax

From Pigbert Wiki

Table of contents

The XMLHttpRequest object

request = getHTTPObject();
request.open("GET","example.txt",true);
request.onreadystatechange = doSomething;
request.send(null);
creation
function getHTTPObject(){
    if(window.ActiveXObject)
        return new ActiveXObject("Microsoft.XMLHTTP");
    else if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    return false;
}
request = getHTTPObject();


function "open"

request.open("GET/POST/SEND","example.txt",true)

  • arg1: what sort of HTTP request you want to make (GET, POST, or SEND)
  • arg2: a file on the server to point the object to
  • arg3: whether the request should be processed asynchronously.


function "send"

request.send(null);


property "onreadystatechange"

request.onreadystatechange = doSomething;

This is an event handler that is triggered when the server sends a response back to the XMLHttpRequest object. It specifies what should be done after receiving a response.


properties made available after received a response from the server

When the server sends a response back to the XMLHttpRequest object, a number of properties are made available.

  1. the readyState property is a numerical value that is updated while the server deals with the request. There are five possible values:
    • 0 uninitialized
    • 1 loading
    • 2 loaded
    • 3 interactive
    • 4 complete
  2. Once the readyState property has a value of 4, you have access to the data sent by the server. This data can be accessed by the responseText property.
  3. If the data is sent back with a Content-Type header of "text/xml", you can also access the responseXML property, which is effectively a DocumentFragment, which can be manipulated using all the usual DOM methods. (This is where the XML part of XMLHttpRequest comes from)
function doSomething(){
    if(request.readyState == 4){
        alert(request.responseText);
    }
}
Personal tools