Javascript: Adding timeout to synchronous REST API call - javascript

I'm going to call a function which makes a Synchronous REST API call. I want to somehow timeout on that function call if it does not return within some time. How do I do that?
callBlahService = function(args){
// make actual rest api call
$.ajax{
// arguments
async: false
}
}
callBlahService({
success:function(data){
console.log("blah successful");
},
error: function(data){
console.log("blah failed");
}
});

Looks like you're using JQuery. There is a timeout setting on $.ajax that should be use: http://api.jquery.com/jQuery.ajax/
Your error handler will get called if the timeout is exceeded.
$.ajax({
timeout: 1000,
success: function(response) {},
error: function(x, t, m) {
if(t==="timeout") {
alert("timed out!");
}
}
});​

timeout
Type: Number
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
http://api.jquery.com/jQuery.ajax/

Related

How do I send through ajax each element from the following array?

Send through ajax each element from the following array. Note: Each request must
be made once the previous has finished.
[‘This’, ‘is’, ‘a’, ‘fake, ‘array’]
I am a little confused by this question because I thought Ajax is asynchronous, meaning the script keeps sending requests to the server without waiting for the reply.
***Was downvoted so going to clarify something: It specifically states in the problem statement that the REQUEST must be made synchronously. I do realize that there are better ways of doing this via def/promises asynchronously so order remains for the result but that isn't the request.
Ajax has a async parameter you can set to false which will block until call completion.
Per documentation:
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
http://api.jquery.com/jquery.ajax/
Example:
$.each(["This", "is", "a", "fake", "array"], function( index, value ) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data : { json: JSON.stringify( value ) },
async: false,
success: function(data) { alert(data);}
});
});
Working fiddler example: https://jsfiddle.net/zm9bb4xk/
I was talking about JQuery Ajax.
So, first, based on documentation, Ajax has many events that run at certain times, for example:
beforeSend (Local Event)
This event, which is triggered before an Ajax request is started,
allows you to modify the XMLHttpRequest object (setting additional
headers, if need be.)
error (Local Event)
This event is only called if an error occurred with the request (you
can never have both an error and a success callback with a request).
complete (Local Event)
This event is called regardless of if the request was successful, or
not. You will always receive a complete callback, even for synchronous
requests.
success (Local Event)
This event is only called if the request was successful (no errors
from the server, no errors with the data).
More in documentation.
Second, following your example (you have to complete this with your own data and this code is not tested, maybe it has some small sintax errors), an approximation is:
// Variables
var myArray = ["This", "is", "a", "fake", "array"];
var globalIndex = 0;
// Function for Ajax Calls
function myFunction(){
$.ajax({
url: 'myURL', // Your own controller/url
type: "GET", // Or POST
dataType: "json", // Or other datatype
data: {
arrayContent: myArray[globalIndex] // arrayContent = your controller param name
},
/**
* A function to be called if the request succeeds.
*/
success: function(data) {
alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
alert(data); // Do what you want with your data, this is an example
globalIndex = globalIndex +1;
// Recursive/next call if current call is finished OK and there are elements
if(globalIndex < myArray.length){
myFunction();
}
},
/**
* A function to be called if the request fails.
*/
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
alert('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
// We don't do a recursive/next call because current call has failed
},
});
}
// First call to myFunction
myFunction();

Timeout in function with ajax jquery

Good afternoon people !
I have the following code in jquery / ajax
$.ajax({
url:'../pujar',
dataType:'json',
type:'get',
cache:true,
});
This code works correctly when I send the php but now I don't know how to use the timeout with ajax.
In another code I use the following structure and I don't have any problem with code.
setInterval(function() {
$.ajax({
url: '../ajaxpujas',
dataType: 'json',
type: 'get',
cache: true,
success: json,
});
function json(data) {
$("#tbodyid")
.empty();
$(data)
.each(function(index, value) {
var table = '<tr><td>' + value.users.name + '</td><td>' + value.id + '</td></tr>';
$('#tbodyid')
.append(table);
});
}
}, 1000);
When I try to use this code , doesn't work correctly. I need to reload every second.
$.ajax({
url:'../pujar',
dataType:'json',
type:'get',
cache:true,
timeout:1000,
});
Docs
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
timeout in $.ajax() sSet a timeout (in milliseconds) for the request to complete, if for any reason the request is not completed with in the time frame the request will abort
You have to use
setInterval(function() {
$.ajax({
url: '../pujar',
dataType: 'json',
type: 'get',
cache: true,
success: function (data) {
}
});
}, 1000);
The "timeout" that you are using in the AJAX request is not the same as setTimeout in javascript. AJAX timeout actually specifies the time in which the request should get timed out.
As per jquery's documentation
timeout
Type: Number
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent.
Hence you are actually setting a timeout for your request (i.e. if the source doesn't respond in 1000ms consider it to be a timeout failure). Thus you have to reload it every second.
What you are trying to do with the setInterval would work. Though I would recommend using setTimeout recursively instead of setInterval for better performance (and the intended effect I guess).

Globally configure all $.ajax requests to support retry on timeout

I need a way to set some kind of timeout function globally with $.ajaxSetup that will allow my Phonegap application to keep retrying an ajax GET or POST every time there is a timeout due to a bad internet connection.
I use Backbone.js so most jquery plugins won't work for this, I would some help writing one global piece of code which will handle retries.
Thank you.
You can use jQuery.ajaxSetup(options).
Set default values for future Ajax requests. Its use is not recommended.
Example
$.ajaxSetup({
timeout: TimeoutValue
});
Apart from that if you want perform call again on timeout, I will suggest you to create wrapper for ajax call like.
function myAjax(options){
var myOptions = {
timeout: TimeoutValue,
error: function( jqXHR, textStatus, errorThrown) {
//textStatus can one of these "timeout", "error", "abort", and "parsererror"
if(textStatus === "timeout") {
//Recall method once again
myAjax(options)
}
}
};
options = $.extend(true, myOptions , options);
$.ajax(options)
}
And Use the function just like $.ajax
Found a solution to make all AJAX calls work with a retry timeout.
$(document).ajaxError(function (e, xhr, options) {
if(xhr.status == 0){
setTimeout(function(){
console.log('timeout, retry');
$.ajax(options);
}, 5000);
}
});

How to set maximum execution time for ajax post with jQuery?

Is there a way to specify maximum execution time of an ajax post to the server so if the server doesn't respond, then keep trying for 10 seconds and then continue with the rest of the code??
Function doajaxPost(){
var returned_value="";
// #############I NEED THIS CODE TO TRY TO POST THE DATA TO THE SERVER AND KEEP
// #############TRYING FOR 10 SECONDS AND THEN CONTINUE WITH THE REST OF THE CODE.
jQuery.ajax({
url: 'ajaxhandler.php',
success: function (result) {
returned_value=result;
},
async: false
});
// ###################################################
alert(returned_value);
some other code
.
.
.
}
Use timeout:
jQuery.ajax({
url: 'ajaxhandler.php',
success: function (result) {
returned_value=result;
},
timeout: 10000,
async: false
});
However, alert(returned_value); will execute just after your call (won't wait for the call to finish).
The JQuery API documentation tells how to set a "timeout".
http://api.jquery.com/jQuery.ajax/
While other answers here are correct, learning to check the documentation for yourself is more valuable than knowing just this answer.
You can set timeout value for your ajax request.
timeout
Set a timeout (in milliseconds) for the request. This will override
any global timeout set with $.ajaxSetup(). The timeout period starts
at the point the $.ajax call is made; if several other requests are in
progress and the browser has no connections available, it is possible
for a request to time out before it can be sent. In jQuery 1.4.x and
below, the XMLHttpRequest object will be in an invalid state if the
request times out; accessing any object members may throw an
exception. In Firefox 3.0+ only, script and JSONP requests cannot be
cancelled by a timeout; the script will run even if it arrives after
the timeout period.
Here is an example:
$.ajax({
url: "ajaxhandler.php",
...
timeout: 10000,
...
});
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
Hopefully, this will help others like me who aren't completely fluent in JavaScript or, more to the point, aren't completely fluent in reading jQuery documentation.
I admit, I looked at the jQuery.Ajax docs, and easily enough found the section that talks about setting a timeout:
timeout
Type: Number
Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
But lacking an example, I was still clueless how to specify the timeout value. The secret sauce is at the top of the article, where it says:
In JavaScript, this translates to this sort of syntax:
$.ajax({
url: "https://example.com/my-endpoint",
...
timeout: 0,
...
});
In the above example (which specifies a timeout of 0 to disable timeouts for this request), each key/value pair (as mentioned in the documentation) appears in the code as [key]: [value]

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Categories