AJAX
Asynchronous JavaScript And XML (AJAX)
AJAX allows web pages to be updated asynchronously by making HTTP requests in the background
AJAX facilitates updating parts of a web page without reloading the whole page
AJAX is a method that relies on the XMLHttpRequest object (to make HTTP requests) and the JavaScript DOM
Typical AJAX Procedure
A DOM event is fired
An
XMLHttpRequest
object is created as part of the event handlerThe
XMLHttpRequest
object sends an HTTP request to a serverThe server processes the request and sends a response back to the browser
The response is read by JavaScript and the DOM is updated accordingly
The XMLHttpRequest
Object
Methods:
new XMLHttpRequest()
abort()
getAllResponseHeaders()
getResponseHeader()
open(method, url, async, user, password)
send()
send(string)
setRequestHeader(header, value)
Properties:
onreadystatechange
readyState
responseText
responseXML
status
statusText
XMLHttpRequest
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var node = document.getElementById("one");
node.innerHTML = this.responseText;
}
};
xhttp.open("GET", "file.txt", true);
xhttp.send();
HTTP Requests
The
open()
andsend()
methods are used to make an HTTP requestopen(method, url, async, user, password)
method: type of request (GET or POST)
url: the URL of the resource
async: true (asynchronous) or false (synchronous)
user: optional user name
password: optional password
An asynchronous request does not have to wait for the server’s response
The send
Methods
The
send()
method is intended for GET requests or POST requests with no URL query datavar xhttp = new XMLHttpRequest(); xhttp.open("GET", "file.txt", true); xhttp.send();
The
send(string)
method is used to POST URL encoded datavar xhttp = new XMLHttpRequest(); xhttp.open("POST", "login.php", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("username=Bob&password=swordfish");
The setRequestHeader
Method
The
setRequestHeader
is used to add an HTTP request headersetRequestHeader(header, value)
header: specifies the HTTP header name
value: specifies the HTTP header value
The onreadystatechange
Property
The
onreadystatechange
defines a function to be called when thereadyState
changesThe
readyState
property contains the status of theXMLHttpRequest
0: request not initialized
1: server connection established
2: request recieved
3: processing request
4: request finished and response is ready
The
status
property contains the HTTP status codeThe
statusText
property contains the HTTP status text
Retrieving the HTTP Response Data
The
responseText
property contains the response data as a stringThe
responseXML
property contains the response as an XML DOM objectThe
getResponseHeader(header name)
method returns the value of a specific HTTP headerThe
getAllResponseHeaders()
method returns all of the HTTP response headers
XMLHttpRequest
Events
readystatechange
: thereadyState
property changesloadstart
: progress has begunprogress
: in progresserror
: progression failedabort
: progression is terminatedtimeout
: progression is terminated due to preset time expiringload
: progression is successfulloadend
: progress has stopped
Abstracting XMLHttpRequest
s
XMLHttpRequest
code typically follows a standard patternThat pattern can be abstracted into a helper function to avoid writing the repetitive
XMLHttpRequest
handling code:function getURL(url, callback) { var req = new XMLHttpRequest(); req.open("GET", url, true); req.addEventListener("load", function() { if (req.status == 200) { callback(req.responseText); } }); req.send(); }