What is readyState and status? - javascript

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!

Related

What is meaning of xhr.readystate===4

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

Possible HTTP Request states after form submit

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).

Server XHR got received event in JS

Situation:
Target API is external and may not be changed in any way. I have a JS client that sends some data to the API on client button click. Something like
$.ajax({
type: "POST",
url: "http://api.url/some_resource",
data: {name: 'John', email: 'john#john.com'}
}).done(function(msg) {
if (msg === 'ok') {
alert('Your Callback Request Sent!');
} else {
alert('Error occurred. Please try later.');long
}
});
When I send the request I have to wait to receive the response from the server to see if it was successful and notify the client if it was or was not.
The problem is that I the API is friggin slow and does not reply directly that it received everything and will process the request, but instead is trying to do all the job like sending email and only then replying. Sometimes it takes about 20s for response to be received (the XHR request response).
Is it possible (jQuery or pure JS) to fire something like "request reached server event" so I would be at least sure there were no connection problems?
Is it possible to fire something like "request reached server event"
No - the client does not know of that event. It only knows a) when it has sent the last bit of the request and b) when it has received the first bit of the response. There is nothing in between but waiting.
To the XMLHttpRequest interface there is the following readyState information available:
Val State Description
---------------------------------------------------------------------------------
0 UNSENT open()has not been called yet.
1 OPENED send()has not been called yet.
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.
so I would be at least sure there were no connection problems?
Well, if there had been connection problems that are detectable to the client, you would've been notified of them.

readyState vs status==200

xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
Above code is from:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp.
Question:
According to this tutorial:
readyState: 4: request finished and response is ready
status: 200: "OK"
When readyState is 4 and status is 200, the response is ready:
since when xmlhttp.readyState == 4, response is ready, why do we still need xmlhttp.status == 200? what is the difference between xmlhttp.readyState == 4 and xmlhttp.status == 200?
The status of the response, xhr.status, is (generally) used to determine whether the request was successful or not. xhr.readyState is simply used to determine the state of the request, such as "has not yet been sent" (0), "complete and response received" (4), etc.
The server is responsible for providing the status, while the user agent provides the readyState.
status indicates if server response is ok.
In general words, when you got an status
500 - 599: the server had an error
400 - 499: this is a client error (Ex: 404 page not found)
300 - 399: then exists a redirect
200 - 299: then it is correct and
100 - 199: means information message
Then the status==200 is getting you a message where the server says: 'Hey man I do the work!'
my analogy : An ambulance carrying a patient is going to a hospital.In this scenario family(client) and hospital (server) needs to keep track of two things
Ambulance reached hospital successfully.(readyState)
Health updates of patient during this process.(status)
If readyState === 4 and status === 200, means everything is all right.In the same way ajax call works.
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
Consider you have an error on your server side code. You request the page, and the readyState will be 4 when the server finishes streaming the response, but the status code will be 500 (or 500-something).
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
for details of response messages
visit
https://www.w3schools.com/tags/ref_httpmessages.asp
The readyState refers to the response of the request - it is 4 when you have finished retrieving the response and there is something to look at. The actual value is still not known, so you need to check the status that has been returned.
onreadystatechange=function() executes only when we get the response from the server.
If we get response from the server means our request is finished which is indicated by 4.And 200 tells us its status that is correct.
"4: request finished and response is ready status 200"
We get status 404 if the page is not found.
Illustration:
You (client) send a package to your girlfriend (server), but requires her signature (200 - signed or 404 - not signed). You can check the status of your package (0 - at post office, 4 - out for delivery). Once the package leaves the facility, it will be marked out for delivery (4). But if your girlfriend is not at home when the package arrives, it will return to the post office as not signed (404).
So, it is possible for a status to be received regarding the package (4) and a status of whether delivery was successful (404). With AJAX, a request can be made to a server. Once the requested information has been obtained (this includes the status of the server - whether the data/document was found), then it is sent back to the receiver (client) for analysis, prior to displaying any content.

Are there useful uses of readyState different from "4" (complete) in a XHR.onreadystatechange callback?

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).

Categories