Is it right to say that the AJAX call has completed after xhr.readystate===4?
Here it says the state is complete. So what does this complete mean?
An Ajax http request has 5 states as your reference documents:
0 UNSENT open() has not been called yet.
1 OPENED send() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
State 4 means that the request had been sent, the server had finished returning the response and the browser had finished downloading the response content.
So, it is right to say that the AJAX call has completed.
Yes, it is correct.xhr.readstate===4 means request finished and response is ready. You can refer this for details.
Here is small example:
xmlhttp.open("GET", "test.txt", true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null);
The above script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete, it displays the responseText to the user with an alert.
Source
Related
I'm trying to submit a form and get the results inpage using AJAX. I call a JS function onsubmit which makes the AJAX call, and includes this code:
request=new XMLHttpRequest();
/* set up request here */
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
/* do what I need */
alert('Success');
} else {
/* do what I need */
alert('Failed');
}
}
However, the Failed alert shows up multiple times (3 at least) before the Success one, so I guess I'm getting many different statuses before the successful one? How can I check which ones I get, and what to expect when the submission is failed? Thanks.
The request goes through four phases. The readyStates. Every time the readystate updates it fires the event. 0 indicates a failure and 4 indicates that the request has finished. the status returns the http code. 200 indicates success. There was an answer and it returned a request body. All other codes indicate there was something wrong on the server side. Eg. 404, 403, or 500. You can safely ignore the other readystates. But catch any status other than 200 as failure.
You only ever get one status, but you get multiple states.
Check to see if the readyState is 4 or 0 (since either of those states indicate that there is no more of the response to wait for).
Then throw an error if it is 0 or test the status if it is 4.
If the readyState is any other value, then ignore it (unless you want to do stuff in other states).
function hello()
{
var request = getXHR();
request.open("GET","A?value="+document.getElementById('a').value+"",true);
request.send(null);
request.onreadystatechange=function()
{
if(request.readyState==4)
{
if(request.status==200)
{
var val=request.responseText;
document.getElementById('a').value=val*10;
}
}
}
}
I found the above code..in an ajax tutorial...I cannot understand the reason for using
request.readyState==4
request.status==200
Can anyone explain me the reason for using this code segment?
Can anyone explain me the reason for using this code segment?
When a request to a server is sent, we want to perform some actions based on the response.
Refer State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
In practice you almost never use any of them except for 4.
status
200: "OK"
404: Page not found
I hope.These will helps you.
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object
readyState: Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status
200: "OK"
404: Page not found
The readystate basically means that the request has finished processing.
200 is the http status for OK. This means it is safe to try and access the data.
Really, use google!
I have got multiple JavaScript ajax requests on my page. Now, on a particular ajax call (triggered by an onclick event), I get 3 error messages back to back. On checking for request.readyState I found that each time the error comes, it's got ready states as 1, 2 and 3 respectively and then it works (readyState=4 obviously).
Here is the ajax request I am sending to the server:
function fetch(parameter){
var myrequest=new ajaxRequest()
myrequest.onreadystatechange=function(){
if (myrequest.readyState==4){ //This property is not equal to "4" for 3 calls
if (myrequest.status==200 || window.location.href.indexOf("http")==-1){
// Code to be executed for successful call
}
}
else{
alert("Error in Request. Request State is: " + myrequest.readyState);
}
}
myrequest.open("GET", url, true)
myrequest.send(null)
}
On triggering the onclick event, I get errors as:
Error in Request. Request State is: 1
Error in Request. Request State is: 2
Error in Request. Request State is: 3
What can be the problem with the request?
Those are XMLHTTPRequest (ajax) states where:
1 => loading
2 => loaded
3 => interactive
4 => ready
At 4, the ajax request is deemed complete and the returned data can be accessed.
You should just drop the else condition.
From the reference I read in MDN, it says
If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived.
This is the A in AJAX.
I have been using AJAX but then I was a little confused when I read that. I think the problem may be that I am not understanding AJAX concept clearly. I know of course AJAX does not refresh the page which means the connection to the server and the response are completely done in the background.
But what I can imagine happening according to that reference is that if I have a code like this in my JavaScript:
//true, therefore process the function while server retrieves url
var xmlResponse;
var url = "http://example.com/file.xml";
xml_req.open("GET", url, true);
xml_req.onreadystatechange = function() {
if(xml_req.readyState == 4 && xml_req.status == 200) {
if(xml_req.responseText != null)
xmlResponse = xml_req.responseXML; //server response may not yet arrive
else {
alert("failed");
return false;
}
};
xml_req.send(null);
Doesn't that mean xmlResponse could be undefined in the sense that the server is still retrieving the data? Could somebody explain what really is the flow of the execution in AJAX technology? Thanks in advance.
I wrote a more detailed article here, but this is the basic idea.
Setting it to true means you are making an asynchronous request. That means the code does not pause until the http request is complete. A synchronous call locks up the browser so nothing else runs. That can cause problems, so people prefer asynchronous.
The XHR object updates us on what it is doing. It gives us the updates with the onreadystatechange event. We register a function with it so we can keep track of its status. The onreadystatechange gets called 4 times. Each with a different state
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
The data is available to us when the readystate is 4.
Now in the code you posted, it is checking for the complete state and it makes sure that the status is 200 [ok]
if(xml_req.readyState == 4 && xml_req.status == 200){
The value for xmlResponse will be undefined if you try to use it somewhere else in the code before it is returned. An example
ml_req.send(null);
alert(xmlResponse );
One of the very first articles on the XMLHttpRequest article might be a good read for you. Apple Article on xmlhttpreq
The important thing to understand is that your onreadystatechange handler is not executed immediately. And it is executed more than once. It may be easier to conceptualize, if you break the pieces out into individual functions:
function makeRequest(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = receiveResponse;
xhr.send();
}
function receiveResponse(e)
{
if (this.readyState == 4)
{
// xhr.readyState == 4, so we've received the complete server response
if (this.status == 200)
{
// xhr.status == 200, so the response is good
var response = this.responseXML;
...
}
}
}
First, makeRequest is called and then exits. Then, as soon as we hear anything back from the server, receiveResponse is called. Each time, we check to see if the response is fully received, and only then do we continue to process that response.
Have you ever used an XHR object to intercept onreadystatechange with a readyState different from "4" (complete) ?
I'm curious to know if you ever trigger a function with the possible different values.
I cannot imagine a real use of the others states. Are they somewhat useful to do something?
Can give some practical examples if any ?
I'm talking about these:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
I use it on an intranet I have developed for notification purposes.
By intercepting the state 3 I can notify the user that the request started.
I also use it to time the requests transmission times. I display the time elapsed between states 3 and 4.
Since I use MooTools I extended the Request class to fire the onStateChange event:
var EarlyRequest = new Class({Extends: Request,
onStateChange: function() {
this.fireEvent("onStateChange", [this.xhr.readyState]);
this.parent();
}
});
On an additional note. The definitions of the states that you posted (from w3cschools) are misleading, these are clearer to me (from http://www.w3.org/TR/XMLHttpRequest/#states):
UNSENT (numeric value 0)
The object has been constructed.
OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
LOADING (numeric value 3)
The response entity body is being received.
DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).