Terminate ajax call after timeout - javascript

I am executing the following ajax call.
I am testing timeout mechanism and thus suspending my server on purpose.
The problem is that although I do receive timeout in the client after one second the call as I see it in firebug still continues.
I guess there should some way to stop the call execution but I did not find one.
$.ajax({
url: url,
dataType: "jsonp",
jsonp: "jsoncallback",
timeout: 1000,
success: (function(w) {
...
},
error: function(XHR, textStatus, errorThrown) {
alert("Error");
}
});
Appreciate the help.

You can try this
...
error: function() {
window.stop()
}
...

Try this Abort Ajax requests using jQuery

Related

Error or fail not being reached when Ajax fails to fetch JSON

I am working on below Ajax code in JavaScript, I am trying to pop up a dialog box when the URL could not load the JSON properly the reason may be either expired token or incorrect token, in any case, I am expecting the code to hit the error or fail but it's not happening. When the URL could load the JSON successfully, success and complete blocks are being hit as expected but nothing is being hit when URL fails. I have tried to use async: false and tried to check with a boolean variable weHaveSuccess but console.log(weHaveSuccess); which is in the last line of the code is getting executing even before success/error is being executed and it seems to me like its still loading asynchronously. I would like to know why error block is not being hit when the JSON load from URL is getting failed.
My code
function checkUser(myURL, newAccessToken, weHaveSuccess) {
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: myURL + newAccessToken,
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
},
success: function (data) {
console.log("Hello 2 " + JSON.stringify(data));
weHaveSuccess = true;
console.log('Message from Success ' + weHaveSuccess);
},
complete: function () {
console.log('Message from Complete ' + weHaveSuccess);
}
}).done(function (data) {
alert("Success");
console.log(data);
}).fail(function (data) {
console.log(data);
alert("Failed");
}).always(function () {
alert("In Always");
});
console.log(weHaveSuccess);
}
Thanks in advance!
AJAX requests are asynchronous. It takes time for a remote request to be made and responded to. You will have to write your post-response code within the success function or call another function from there, not within the same scope as where the call is initiated.
I am taking a bit of a guess here about what your server returns on failure. An AJAX request success means simply that a 200 OK response was received, without any consideration of the contents of the data. If an error is simply a change in the data you will need do one of the following to show an error:
Have the server set a status code header on failure, perhaps 400 Bad Request.
In the success function look within your data for whatever error response you are expecting and trigger the alert() there.
First of all the console.log(weHaveSuccess); fires first, because the $.ajax() is asynchronous while console.log is not so ajax will be triggered and return the promise when finishes, but the browser will continue with the script.
In the jQuery ajax docs says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
It's hard to debug without seeing the response, maybe you can add some info from the network or a URL?
How about if you try the following:
Add the jsonp setting to your $.ajax() function for the callback that will handle the response and console.log there:
function myCallback(data) {
console.log(data);
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: myCallback,
...

Timeout not working in ajax post request

I am not able to make ajax error callback function of after 3 seconds. I tried with timeout, but it will not switch to error callback after specified time! I am not able to get the alert Got timeout.
When I referred similar questions in this site with similar problems it didn't helped out. They all use ajax GET type. I am using jquery 1.10.1 library.
script :
$.ajax({
type: 'POST',
timeout: 3000,
url : "http://mydomain/Services.asmx/Best_Scores",
dataType: "text",
async:false,
crossDomain:true,
data: "strJsonRequest="+scoredata,
success: function (data) {
// Success code ...
},
error: function (data, textStatus, errorThrown) {
if(textStatus == "timeout") {
alert("Got timeout");
}
}
});
Any solution ?
Fix :
Change async : false to async: true
Reason :
A synchronous AJAX call blocks until the request has been finished. Implementing a timeout is not possible for technical reasons, because the AJAX call would have to be executed later.
If an AJAX call is executed later, the function somehow has to implement a blocking feature, to stop the code from running further after the AJAX call, and execute it again after a timeout - not possible.
Today, (in 2019) I still have this problem.
I have an ajax call too long (depending from Date Start-> Date End) php script.
and after some minutes I get error 500, async: true don't help.
The call is:
$.ajax({
type: "GET",
dataType: 'json',
url: 'mymscript.php',
contentType:'application/json;charset=UTF-8;',
data: $('[name="myForm"]').serialize(),
async:true,
timeout:0,
success: function(response){
...
I resolved using:
side PHP:
set_time_limit(0);
ignore_user_abort(true);
at begin of script.
echo ' ';
flush();
ob_flush();
in the middle of script (for example in main loop every day). This help to let client to don't disconnect (I think that is the main problem).
Using this I continuosly write spaces befor the final json.
Fortunately jquery trim spaces before to parse the json and, in the end, the json is valid.
So I can catch response object to know if script is ended with errors or warnings.
I Hope this help somebody.

use paging with ajax call in a while loop

In a javascript function I make a call to the server and get batches of 10 records back. I need to do this untill I've had all records.
To start I made a while loop where in the error callback of the ajax call I would end the while loop.
Halfway through I started to realize that that would not work, as the ajax call is async and I would thus fire loads of requests in the loop. I'm sure there is a standard pattern to do this but I don't know how.
How can I do the ajax call in a loop and perform it as long as the call is not returning an error?
Pseudo code I was building:
var stillRecordsAvailable = true;
while (stillRecordsAvailable) {
// get the next batch of records
$.ajax({
url: '/getrecords.json',
data: {data_set_id: dataset.id},
type: 'GET',
success: function(data, textStatus, xhr) {
// do something
},
error: function(xhr, textStatus, errorThrown) {
// nothing left to do
stillRecordsAvailable = false;
}
});
Thanks for pointing me in the right direction
You'd probably want to just wrap the ajax call in a function that is called on the ajax success callback:
function getRecords(data, textStatus, xhr) {
if (data) {}; // do something...
$.ajax({
url: '/getrecords.json',
data: {data_set_id: dataset.id},
type: 'GET',
success: getRecords
});
}
This will only work if your server/API returns an error when no more records exist; however, this may not be the best pattern. A more elegant way of tracking asynchronous event state is through a deferred/promise pattern. jQuery has a great implementation: http://api.jquery.com/category/deferred-object/

Delay between repeated AJAX call to a web method

I have a ASP.Net web app with jquery implemented on the client side. within a while loop, the client side jquery script makes an asynchronous call to a web method in the server side code. The call returns the status of a long running server side task which jquery uses to update the user. The goal is to have jquery repeatedly call the server until the status is complete, once done it breaks out of the while loop and notifies the user thatthe task is complete.
My problem is that the below code runs in a while loop, but I want to make it delay or sleep between each call in order to prevent overwhelming the server with status requests. I tried calling setTimeout in the code below, but it only works with the initial ajax call, every subsequent call occurs back to back. Is there a way to efficiently delay each subsequent call to the server? Is this the most efficient way to achieve the kind of behavior I'm describing? Ideally I'd like a 2-5 second delay between each call.
I have the following code
Client Jquery:
var alertTimerId;
$('input[name=btnStatus]').click(function () {
var result = false;
//Loop while server reports task complete is true
while (!result) {
alertTimerId = setTimeout(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
if(msg.d != false)
result = msg.d;
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}, 2000);
if (count > 0) {
count--;
}
}
});
Server Side ASP
[System.Web.Services.WebMethod]
public static bool GetStatus()
{
return result;
}
How about something like the following? The idea is that the Ajax call is encapsulated in a function, doAjax(), and then from within the Ajax success handler if the result is false you use setTimeout() to queue up another call to doAjax, otherwise you take whatever action you want to take for a true result. (You could optionally call doAjax() from the Ajax error handler too.)
$('input[name=btnStatus]').click(function () {
function doAjax() {
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
if (!msg.d)
setTimeout(doAjax, 2000);
else {
// Success! Notify user here
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}
doAjax();
});
(Note: I've removed the if statement with count, since it seemed to have no relevance to the question. If your real code uses it just update it within the Ajax success handler too.)
Underscore.Js has a .throttle() helper function:
throttle_.throttle(function, wait)
Creates and returns a new, throttled version of the passed function, that, when invoked
repeatedly, will only actually call the original function at most once
per every wait milliseconds. Useful for rate-limiting events that
occur faster than you can keep up with.
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

$.ajax call with async:false and timeout expected

I've a web application which calls a webservice with ajax. This webservices returns me the configuraiton for my app, so the ajax call needs to be set at {async:false}.
Everything works fine when my server is up, but in the case it's not, my browser just freezes. Even if I set a timeout in my ajax call setup.
I've a error handler function which is never called even if the timeout is passed.
Someone has ever been confronted to that situation ?
#Edit : My problem can be solved by doing asynchronous call
As the browser is single threaded it would be better to process the config
returned in the callback success, and handle any errors in the error callback.
$.ajax({
url: "mydomain.com/url",
type: "GET",
dataType: "json",
data: $.param( $("Element or Expression") ),
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});

Categories

Resources