Possible HTTP Request states after form submit - javascript

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

Related

Confusion about ajax

There is a way to send or get request using ajax which allows to send data without page reload like everything happens behind the scene i found a script for doing that but some of the functions within aer confusing can anyone explain me what are they and why we are using those
data.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
data.onreadystatechange = function () {
if(data.readystate == 4 && data.status == 200) {
data.return_data = data.responseText;
document.getElementById("response").innerHTML = return_data;
}
}
data.setRequestHeader What is the use of this function and why we are using this
onreadystatechange same for this and not understanding why if condition is used
Help would be highly appreciated
You are using XMLHttpRequest to send/get the data.
The function setRequestHeader is used to set value of header params before sending request to server.
The condition if(data.readystate == 4 && data.status == 200) is used to check what is the status and state of request. By using if condition you can verify the success of your request and take needful action after success. Below is the list of possible status and state.
Possible states with 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
to see list of all possible status codes please refer to developer.mozilla.org

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

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!

Ajax request not working three times and then works

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.

Firefox XMLHttpRequest sets error flag on a 302 response

I have a web app driven by a servlet that times out users' sessions after a period of inactivity by redirecting to a login page. I had code in place on the web client that checked for this, essentially similar to the following:
function error(request, errtype) {
if (request.status == 302) {
// Display a "timed out" dialog, then:
window.location = request.getResponseHeader("Location");
}
}
However, recently this scheme stopped working; on timeout, the request.status was 0. Using Firebug I could see that the same HTTP 302 response was being returned.
I read the spec for XMLHttpRequest carefully, and found this section:
If the redirect does not violate security (it is same origin for instance), infinite loop precautions, and the scheme is supported, transparently follow the redirect while observing the same-origin request event rules.
Otherwise, this is a network error.
I hadn't even known that clients were supposed to automatically follow redirects that they get in response to Ajax requests; the browsers I care about didn't do that before, since my code above used to work. I recently upgraded my version of Firefox, which now perhaps is following the spec more closely. The network error prescribed by the spec would explain the zero response code I'm seeing. However, the redirect I'm getting is to the same host (albeit on a different port), there shouldn't be an infinite loop, and the scheme remains HTTP, so I don't understand why I'm getting a network error.
Any ideas?
how you are you getting to this function? if you're only sending it to "error" on a 200 status obviously this wouldn't work...
request.onreadystatechange = function( )
{
if( this.readyState == 4 )
{
// if we got a 200
if( this.status == 200 ){ /* cool */ }
// if we got anything else
else { error( this, this.status ); }
}
};
But I'm assuming you know this. Also, you should probably include .href at the end of window.location and possibly a default location just in case
// Display a "timed out" dialog, then:
window.location.href = request.getResponseHeader("Location") || defaultPage;
If this doesn't work, you might wanna try a different status in the onreadystatechange method, as some browsers may interpret a non 200 status as an error. These could be (from that same spec you're reading from):
0 (if it's considered aborted after unset, though unlikely)
2 (headers-sent) as that 302 code is actually a HTTP header
good luck!

Categories