I have a script that fetches raw JSON data for an image from Flickr and displays it on the page. I want to provide real-time feedback using readyState during the process.
Currently, my code checks if the readyState is 4 and the status is 200 before adding the JSON data to the page.
Sample Code:
function sendRequest (request) {
//Request contains tags entered by the user to search images on Flickr.
x = new XMLHttpRequest();
x.open("GET", request,false);
x.send(null);
if (x.readyState==4 && x.status==200)
{
document.getElementById("resultsContainer").innerHTML="Raw JSON Data: <br>"+x.responseText+"<br><br>";
}
}
The received value is added to the resultsContainer div. I also attempted to provide feedback in the same div like this:
if(x.readyState==3){
document.getElementById("resultsContainer").innerHTML="Processing Request";
}
However, the feedback did not show up. Why does it recognize ready state 4 but not 3?
I tried using the onreadystatechange function but it didn't work as expected. How can I update the UI while the request is ongoing (readyState == 3)?
UPDATE:
UPDATED CODE:
function sendRequest (request) {
x = new XMLHttpRequest();
x.open("GET", request,true);
x.send();
x.onreadystatechange = function () {
if (x.readyState==4 && x.status==200){
document.getElementById("resultsContainer").innerHTML="success <br>"+x.responseText;
}
if(x.readyState==3){
document.getElementById("getIms").value="Processing";
}
}
}
The value of element getIms changes to "Processing" only when the response is received and displayed in the results container.