Processing server response
Every XMLHttpRequest object transition between 5 stages to complete a request. The XMLHttpRequest object has a property called readyState that you can check to verify in which stage your request is:
Value | State | ReadyState Description |
---|---|---|
0 | UNSENT | Once the XMLHttpRequest object is instantiated. No method has been called. |
1 | OPENED | Once the open method has been executed and it was successful. |
2 | HEADERS_RECEIVED | Once the send method has been executed and it has received the HTTP response headers. |
3 | LOADING | After the Headers are received and while the HTTP response content is being loaded. |
4 | DONE | Once the HTTP response content is completely loaded. |
Once the readyState is 4, it means that your request is completely processed and you could go ahead and perform the update you need in your webpage.
The XMLHttpRequest object has a property used for checking the readyState on every status change. This property is the onReadyStateChange, so when a response is received this function will be called on each status change and when the response is complete (in DONE state) you can execute the code to update the webpage
xmlHTTPRequest.onreadystatechange=function()
{
if (xmlHTTPRequest.readyState==4 && xmlHTTPRequest.status==200)
{
//Execute the update of the webpage
}
}
AJAX data formats
Upon sending an XMLHttpRequest request to the server, we will have a response. This response could be in two different formats: plain text or in XML.
- Plain text: we could receive just a text, a word, a sentence (JSON is actually a sentence)
- XML: the response we received will be XML encoded, so our JavaScript may need to perform some transformation to display it.
XML
The eXtensible Markup Language was created to provide some structure to the information exchanged between multiple systems. It provides a way to store this information and to transport it.
Basically with XML you could create your own language to store your information, for instance:
<record>
<from>John Doe</from>
<to>Everyone</to>
<title>First XML Record</title>
<description>This is the first of many XML records</description>
</record>
To access an XML response, the XMLHttpRequest object has a property called: responseXML.
Once you have the response in a JS variable, you can access the different nodes of the XML with standard DOM functions: i.e: getElementsByTagName.