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).
Related
Using Cordova 8.0.0, iOS 12.1.2, trying to make a GET request to my server.
I can make requests successfully to the server, but if for whatever reason it takes longer than 10 seconds then it fails. It DOES work if it takes any amount of time less than that.
This only occurs for me in iOS, the Android build of the app does not show this behaviour and respects the timeout I've set below.
Example snippet:
$.ajax({
type: "GET",
url: actionUrl,
data: data,
cache: false,
dataType: "xml",
timeout: 300000,
async: false,
beforeSend: function (request) {
request.setRequestHeader("user", settings.userId);
request.setRequestHeader("sid", settings.sessionKey);
},
success: function (results) {
callback(results);
},
error: function (e) {
if (!surpressError){
main.ajaxError(e);
}
main.stopLoading();
if (errorCallback){
errorCallback(e);
}
}
});
Screenshot of request timing
If I make async: true or just take that bit out, the request CAN take longer than 10 seconds to complete but with this legacy app I'd rather not have to change more of it around than I have to to accommodate the switch.
I've also tried adding <preference name="loadUrlTimeoutValue" value="300000" /> to my config.xml, and timeouts of less than 1 minute (30000) but that does not help.
Is there another way I can ensure the timeout is longer than 10 seconds that I have missed?
I managed to work around the issue by removing async: false (thanks charlietfl) and doing:
$.ajax({
//as above
}).done(function(res) {
callback(res);
});
This allowed the request to continue, and upon testing with other timeouts now appears to respect that as well. I also needed to move some displaying code on the receiving end of this request to inside the callback.
Ref: jQuery.ajax() method's async option deprecated, what now?
I have a method which checks for notifications and executes a js.erb in return.
The JS which is triggering this method is given below:
setInterval(function () {
$.ajax({
url: "http://localhost:3000/checkNotification",
type: "GET"
});
}, 15000);
This is working great but I am worried about the performance of the site once it will be in production.
Will this cause a performance issue?
If yes, is there another way to solve this problem?
one suggestion I would make is to take advantage of the callback function of ajax so that if a request takes longer than expected it will not fire again until the last one completes
function checkNotifications(){
$.ajax({
url: "http://localhost:3000/checkNotification",
type: "GET",
success: function(){
setTimout(checkNotification, 15000);
}
});
};
also if for some reason the server were to respond with a 500 error, it would prevent the function from continuing
I am facing a serious issue... Whenever i use Ajax to send a request and get an response my browser got hanged.. and show no loading etc...
But when i response is retrieved from the Ajax then browser and page again start working...
Below is the code that i used.....
function ShowContestStatus(contestID)
{
$("#showContestDetails").html('<div class="loadercontest"><img src="assets/images/loading.gif">Loading Contest....</div>');
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', true);
$.ajax({
url:"process/processMyContest.php",
type:'POST',
cache:false,
async:false,
data : {act : 'showcontest', cid : contestID },
success:function(result)
{
$("#showContestDetails").html(result);
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', false);
}
});
}
Please help me on this... i want to get the same response as on other websites when you send a request and they are using ajax the page neither hanged and also each processing like scrolling etc is visible ......
So please suggest me good ideas.... so i can get rid of it and make my ajax smooth for page without effecting and irritate the other person by hanged...
Thanks in advance...:)
The problem is async:false... Since your ajax request is synchronous the script execution will wait for the request to complete to continue..
Since browser uses a single threaded execution pattern(either it will execute script or repaint or wait for user events at a time- not all at the same time), your browser tab will stop listening to user(so it will look like it is hanged)
function ShowContestStatus(contestID) {
$("#showContestDetails").html('<div class="loadercontest"><img src="assets/images/loading.gif">Loading Contest....</div>');
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', true);
$.ajax({
url: "process/processMyContest.php",
type: 'POST',
cache: false,
//remove async: false,
data: {
act: 'showcontest',
cid: contestID
},
success: function (result) {
$("#showContestDetails").html(result);
$("#RadioGroup1_0, #RadioGroup1_1, #RadioGroup1_2").prop('disabled', false);
}
});
}
Ajax.async
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() or the deprecated jqXHR.success().
Make async:true for making the browser listen other events while running the ajax code.
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/
Probably best to revise the question:
I have an ajax call in my code and I want to cancel the call immediately after it is sent. Basically, I don't want to wait for a response, I just want the entire request to be sent from the client. Could anyone provide some ideas on how to accomplish this?
I have tried the following in Chrome, however it seems that the request is never actually sent (I am logging received requests on the server side).
Basically:
var sendRequest = jQuery.ajax({
url: '/awesomeness.txt',
dataType : 'json',
timeout: 2000,
cache: false,
success: function(result) {}
});
sendRequest.abort();
I have also tried setting a timeout of 1, but bizarrely if I load the page from a new browser the request is not sent (if I refresh the page it is sent).
As easy as just:
jQuery.ajax({
url: '/awesomeness.txt',
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {/*run awesome code*/}
success: function(result) {}
});
// call whatever you want after send
afterSend();
So there is no built in jquery.ajax event for that but you may just call the function right after $.ajax();
Just call YOUR_COOL_FUNCTION after your code block.
This will work because ajax requests use callbacks, so it will not block the current execution for the sake of the performed request, but it will make the request, then move on to your code, so it's as simple as putting any desired block of code after this AJAX call.