Ajax request not working three times and then works - javascript

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.

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

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.

Ajax - I need to check whether a valid session exists before every AJAX requests

I'm working on a project which uses user authentication. I'm facing a issue with my AJAX requests if there is no authenticated session present when the request is made.
I've a session timeout of 3min, so if the user keeps idle for 3 min then do some action which causes a AJAX request then the request will fail and return a 403 error. Here What I'm planning to do is intercept all the AJAX request from the page and sent a ping to the server which will return a JSON object saying whether there is a valid session. If there is one then the client will continue with the current request else it will reload the current page which will take the user to the login page and the user has to provide the credentials again.
Here is my implementation.
$("#param-ajax").ajaxSend(function(evt, request, settings) {
var pingurl = GtsJQuery.getContextPath() + '/ping.json';
var escapedurl = pingurl.replace(/\//g, "\\/");
var regexpr1 = eval('/^' + escapedurl + '\\?.*$/');
var regexpr2 = eval('/^' + escapedurl + '$/');
// Proceed with the ping only if the url is not the ping url else it will
// cause recursive calls which will never end.
if (!regexpr1.test(settings.url) && !regexpr2.test(settings.url)) {
var timeout = false;
$.ajax({
url : pingurl,
cache : false,
data : {
url : settings.url
},
async : false,
complete : function(request, status) {
if (status == "error") {
try {
// GtsJQuery.getJsonObject() converts the string
// response to a JSON object
var result = GtsJQuery
.getJsonObject(request.responseText)
if (result.timeout) {
timeout = true;
return;
}
} catch (e) {
// ignore the error. This should never occure.
}
}
}
});
// Reload the window if there is a timeout -- means there is no valid
// sesstion
if (timeout) {
window.location.reload();
}
}
});
Here everything work fine included the window.location.reload(), but the original ajax request is not aborted. Since the original AJAX request is not aborted after the page reload is triggered, the AJAX request also is sent to the server. I want some mechanism which will allow me to abort the original request if the timeout turns out to be true.
This post offers some answer, but the issue remains with the third party plugins like datatables which uses AJAX. We cannot write a error handler for those AJAX requests.
Thank you.
If I am understanding the situation, you do not need any of that. In your original ajax request, simply add an error function that will redirect the user.
errHandler = function(XMLHttpRequest, textStatus, errorThrown) {
if( textStatus.match(/forbidden/i) ) {
redirectUserToLoginHere();
}
}
$.ajax({
success: yourFunctionHere,
error: errHandler
})
Then you might be able to make some ajax wrapper which always has that errHandler so you don't have to place it in every single ajax call.
EDIT:
after some experimentation, if an 'ajaxSend' handler throws an Error, then the original request will never be sent.
Also, if the handler does
document.location = '/login';
then the original request is never sent.
Hopefully that helps :)
I changed my concept now, I'm checking for the xmlHTTPRequest in the server side using the request header 'x-requested-with'.
If it is a xmlHTTPRequest then 'x-requested-with' will have the value 'XMLHttpRequest'. Both the javascript libraries(EXTjs and jQuery) I'm using sets this header correctly.
Here is my server side code
boolean isAjaxRequest = StringUtils.endsWithIgnoreCase(request.getHeader("x-requested-with"), "XMLHttpRequest")
EDIT
If the given request is a ajax request the response will be json data which will have status 403 and it will contain a key called timeout with value true
ex: {timeout: true, ....}
Then we will handle this in the $.ajaxError() event handler will handle the error. If the error status is 403 and the timeout value is true then I'll reload the page.

Categories