readyState vs status==200 - javascript

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.

Related

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

JavaScript POST Request Issue

So I'm creating a mobile application using Intel XDK, I am sending a JavaScript POST request of a username and password. I also did some research on the HTTP status codes and found this:
200 OK - Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.
201 Created - The request has been fulfilled and resulted in a new resource being created.
202 Accepted - The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.
So I would assume that when a new user is inserted through a POST request the status would be 201. However when I had this code:
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.status == 201) {
alert("User created.");
} else {
alert("Error!");
}
}
It would show the "Error!" and not "User created." But when I added this on to the code:
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.status == 201 || XMLHTTP.status == 200) {
alert("User created.");
} else {
alert("Error!");
}
}
It showed "User created." So I was wondering how come the status is 200 even though I'm sending a POST request to insert in to a database.
Secondly, it alerts the "User created." 4 times? Is that because it is in the function onreadystatechange so it changes each time and is alerted? If so I can I make it so that it only alerts one? Should I have an if statement wrapped in a setinterval as shown below:
setInterval(function () {
if (XMLHTTP.status == StatusNumberHere) {
alert("Blah");
}
}, 10);
Very few websites use those headers, your back-end probably just sends a 200 even though the request was successful in inserting data.
About your second question, the reason your alert is triggered four times is because onreadystatechanged is called four times, each with a different readyState:
Server connection established
request received
processing request
request finished and response is ready
So you probably want to add XMLHTTP.readyState === 4 to your if statement so it in the end becomes:
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.status === 200 && XMLHTTP.readyState === 4) {
alert("User created.");
} else {
alert("Error!");
}
}
The status returned is based on how the server decides to handle it, in most cased you will simply get a success (200), so there is no issue or abnormality with what you have done.
setInterval = hack, avoid at all costs unless implementing some actual interval function.
You can check the the readystate of the XMLHTTP request with
XMLHTTP.readyState == 4
to filter out only the completed event.
Here is a list of the ready state events:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

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.

What is readyState and status?

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!

How to handle ajax call when there is no response from the server

I have an ajax call for some data (using jQuery). after the user clicks "submit" (and the ajax call has been sent) I am displaying a "Please wait..." message that disables everything until the request returns (so the user won't double click or click other things and mess things up).
It works great when there is any kind of error - the "Please wait..." disappears and I am displaying the user what went wrong.
But what happens if the server don't return me anything back because of communication error?
The solution I found for that is to set a timeout of 10 seconds for the "Please wait.." message that after that time it disappears and displays and error that "The communication failed". I assume that if the server didn't respond after 10 seconds then it will not respond at all - but that it false assumption.
The problem is - how can I be sure that after 20 seconds the server won't return something back? The scenario that might happen is that the user click submits --> 10 seconds later he get an error message --> 5 seconds later server response and confuses the user
How do I make sure that after I hide the "Please wait.." message nothing will pop up from the server?
when you send a request to a server. a connection is opened and its kept open unless the server responds.
1.if due to some error on the server side it cannot respond then a response code of 5xx is sent back generally (503)
2.if due to some connection issues the connection is terminated prematurely then also jquery would take that as an error.
1.so if you wanna wait for the server to send a request or connection termination (which ever occurs earlier) then u can use the completed option in the jquery ajax.
2.and if you are in a condition in which server isnt responding even after 20 secs and you think that it should have responded by now use timeout.
3.finally if your problem is that you are using some kind of customized(hand made http server) which doesn't end a request even if it encounters some error then atleast customize it enough so that it sends back some response code(because this is HTTP model of request and response)
You can handle something like this
if ( request.readyState == 4 ){ // 4 is "complete"
if ( request.status == 200 ){
// HTTP OK, carry out your normal Ajax processing
// ...
}else{
// something went wrong, report the error
error( "HTTP "+request.status+". An error was ยป
encountered: "+ request.statusText );
}
}
(or)
$.ajax({
type: "post",
url: "somepage.html",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Generate a unique token when you fire a request,
keep a list of valid tokens,
remove tokens when the request times out/fails,
check if token is still valid before executing success/error callbacks.
The same pattern can be adapted for a situation when you need to send frequent repeating requests (e.g. autocompletion/result filtering) and only the latest one's handler should fire.

Categories