Ajax Callbacks

Full Stack Web Development Learnings
Just another WordPress site
AJAX stands for Asynchronous Javascript and XML
also knowns as …
XML HTTP Request (XHR)
The AJAX/XHR process consists of the following:
This is done by creating an object variable using the XMLHttpRequest() function:
var xhr = new XMLHttpRequest();
Create a function that will be called once ready state has changed to status 4:
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//action
}
};
Use the .open() function:. eg:
xhr.open('GET', 'sidebar.html');
Pass info to send (in the parenthesis) to the server:
xhr.send();
Each stage of the process involves a readyState. Each step changes the ready stage of the request. A callback responds to the change in that state
An XML HTTP request object’s readyState property holds a number from 0 to 4. Zero to 3 represents stages from when the object is created to when the response is coming. ReadyState 4 is when the web server has sent everything it’s going to send.
Status Property
The object also returns a status as per the following
200 – 0k
401 – not authorised
404 – not found
500 – database error
eg. To create a callback when the status is ok. The status has a property of .statusText to provide further info:
if (xhr.status === 200) {
//action
} else {
alert(xhr.statusText);
}
Use the XHR object’s responseText property:
xhr.responseText;