This question already has answers here:
jQuery - Call ajax every 10 seconds
(4 answers)
Closed 6 months ago.
I'm a newby in web development. Sorry about basic questions.
I have a code block with ajax. It takes data from api, and it has to apply every 10 seconds db updates to page. But it's didn't worked. Why my setTimeout() or setInterval() code getting too much response? I tried both of them.
$(document).ready(function() {
sendRequest();
function sendRequest() {
$.ajax({
url: "http://127.0.0.1:8000/studentsapi",
dataType: "json",
success: function(data) {
$('#first_name').text(data[0].first_name);
$('#last_name').text(data[0].last_name);
$('#age').text(data[0].age);
$('#gender').text(data[0].gender);
},
complete: function(data) {
setTimeout(sendRequest, 10000); //
}
});
}
});
In terminal:
As I understand the response time of your API is fast and you just need to clear the timeout. For example:
const timeout = null;
// Your request code
complete: {
if (!timeout) {
timeout = setTimeout(sendRequest, 10000)
return
}
clearTimeout(timeout)
}
Also try to make a research on debounce and throttling it can help you achieve that easier, because you use JQuery as I see.
Also you can just use setInterval outside the complete property.
setInterval(request, 10000)
No need to do it inside complete property unless it is a requirement
Related
I need to write a setInterval function in javascript. Thi is the code:
var myTimer=setInterval(function(){
var time=0;
$.ajax({
url:'...'
type: "POST",
dataType:"",
success: function (response) {
if(response=="true" || time>=10000){
clearInterval(myTimer);
}
time=time+1000;
},
error: function () {
alert("FAIL");
}
});
},1000);
I don't know why It doesn't stop in clearInterval. Anyone can help me?
You've claimed that the code does "come in the 'if'", so I assume the clearInterval call is actually being made.
Given that, the most likely explanation is that the interval is being cleared (after all, select isn't broken), but before the first "true" response, you've already made more than one ajax call, and the other ones you're seeing are ones scheduled before the interval was cleared.
E.g., your code runs and:
Fires off ajax call #1, which takes more than a second to complete
Fires off ajax call #2
Ajax call #1 completes but isn't "true"
Fires off ajax call #3
Ajax call #2 completes and is "true", clearing the interval
Ajax call #3 completes
Mixing two separate asynchronous intervals (one via setInterval and one via ajax) is asking for trouble.
If the goal is to make the request once a second and stop when you get back "true", I would have the success handler schedule the next call, e.g.:
(function() {
var time = 0;
var started = 0;
start();
function start() {
started = Date.now();
$.ajax({
url: '...'
type: "POST",
dataType: "",
success: function(response) {
if (response != "true") {
// Schedule the next call to occur one second after we
// started the previous call; or almost immediately if
// the call took more than a second to complete
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
time = time + 1000;
},
error: function() {
alert("FAIL");
}
});
}
})();
Let me illustrate the expected and the actual scenarios to make things clearer.
Scenario #1
The image below shows the case where all your ajax requests complete before one second. You will notice that ajax callback success (or error) functions will execute only before clearInterval (which is what you always expect).
Scenario #2
When some of your ajax requests take more than one second (which is probably what happens), then your ajax callbacks can fire before / after / before-and-after the clearInterval, which makes you feel that your setInterval doesn't stop.
Note that your time variable is useless because it's a function-scoped variable that you initialize to 0 every function call. And even if it's a global variable, it'll only clear the interval in the 11th success function callback, and nothing guarantees how long these 11 successful requests will take.
Solution
As T.J. Crowder suggested, it's better to schedule the next ajax call in the success callback of the previous one, which guarantees that your ajax requests fire sequentially (only one at a time).
Note: Because you edited your question after his answer, then you'll also need to edit the if condition like this:
success: function(response) {
if (response != "true" && time < 10000) {
setTimeout(start, Math.max(0, 1000 - (Date.now() - started)));
}
}
This question already has an answer here:
Run function if jQuery.ajax waiting for respond long enough
(1 answer)
Closed 8 years ago.
I know about the timeout setting for the ajax call. But what i'm wondering is, is there a way to display a message to the user if an ajax call is still processing but taking longer than x seconds.
E.g.
During an ajax call, if it takes longer than 10 secs tell the user, "call taking longer than expected"
I'd say your best bet is to use window.setTimeout for however long you want to wait for before showing your notification, and then add a window.clearTimeout line to your success callback in your $.ajax() call:
var loadingTimeout = window.setTimeout(function() {
// show your warning here
alert('Still loading :P');
}, 10000); // 10000ms = 10sec
$.ajax({
url: 'http://your/url/here',
dataType: 'json',
type: 'GET',
success: function(r) {
window.clearTimeout(loadingTimeout);
// your results logic here
}
})
Sure, just setTimeout() yourself another function that checks some global variable that gets set by the ajax completion callback. In that function, if the ajax call is still outstanding, show a message.
This question already has answers here:
Abort Ajax requests using jQuery
(18 answers)
Closed 8 years ago.
I would like to stop an ajax call in jquery, which is not working
var xhr = null;
xhr = $.ajax({
url : 'www.example.com?some-large-call',
success : function(responseText) {
// some DOM manipulation
}
});
$("#button").click(function() { xhr.abort() });
I referred the below link
http://www.stoimen.com/blog/2009/09/29/jquery-stop-an-ajax-call/
this probally has more XHR..
Please see this answer:
jquery abort() ajax request before sending another
From the link:
every time you do ajax request, add to array:
requests.push(
$.ajax({
type: 'post',
url: '/test.php',
data: search_data,
success: function(data) {
$('#catalog').html(data);
}
}));
Then, when you want to stop calls..
loop through array and abort all calls..
for(var i = 0; i < requests.length; i++)
requests[i].abort();
Thanks
xhr.abort() it will cause the client to stop listening for the event, but probably it may not stop the server from processing it.
Provided the code you've pasted is the code you're actually using it's no wonder it doesn't work.
As it states on the site it is just pseudo code to illustrate an example. There is no AJAX request there and nothing to stop (at least nothing large enough to be able to stop)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using following JS code to call a web handler.
This code calls the handler perfectly JUST IN IE and not FF.
$.ajax({ type: "GET",
url: "../MasterPages/AHMHandler.ashx?T=1",
dataType: "HTML",
success: function (msg) {
document.getElementsByName('cartId')[0].value = msg;
}
,
error: function (e) {
return false;
}
});
Sleep(2000);
What is the problem with my code?
Having seen the Sleep() call in your code, and your comment about alert(), I would say that your problem is with a lack of understanding of how Ajax code works.
When you mak an Ajax call, it is called asynchronously. This means that the call is made, and then the rest of your current function carries on running without stopping to wait for the ajax code to run.
The ajax success function will be called eventually, but only when the http request is complete. In the meanwhile, your current function will carry on running.
The point here is that you cannot rely on a given sequence of events if you have code in the same function that runs after the ajax call is made.
Putting a Sleep() there might make it appear to work because some browsers might see the sleeping time as an opportunity to run the ajax success function, so your code seems to run in the right order. Putting an alert() there will be even more likely to make it work, because the alert() will generally take more time before it is cleared, so the ajax function has more chance to run.
But you should not rely on either of them to get your execution sequence right.
What you should do instead is put the code that you want to run after the ajax call inside the success function. This is the only way to be sure that it will be run after the ajax call is finished.
Hope that helps.
[EDIT] Further clarification after OP's comment:
Spudley, Sleep Function is my own function to keep browser from being redirect for like 2 secs. function Sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds) { break; } } }
Just for ref, a sleep function like that is a really terrible idea in Javascript. You should use a setTimeout() for that kind of thing.
However, the point is still the same -- you have code that runs after the $.ajax(), and it will be blocking execution of your ajax success function. If you're doing a redirect right afterward, then the success function probably never gets a chance to run.
An alert() would indeed make it work that because the success function will find a slot to run when the alert is cleared, before Sleep is called, but you shouldn't rely on that.
The answer remains the same: You should put the code that you want to run after the ajax call inside the success function.
Here's a your code with the changes made:
$.ajax({ type: "GET",
url: "../MasterPages/AHMHandler.ashx?T=1",
dataType: "HTML",
success: function (msg) {
document.getElementsByName('cartId')[0].value = msg;
setTimeout(function() { //this instead of your Sleep function
//this is where you need to do your redirect, or whatever else you're doing after the ajax completes.
}, 2000);
}
,
error: function (e) {
return false;
}
});
//don't put **any** code here after the ajax call! put it in the success function.
There is a page and I want periodically to make "background" ajax requests. So the page is loaded then it should send ajax requests in a certain amount of time.
I might use cron for that. I have never use previously so I'm wondering if it would fit for that task. Is there any other more simple way?
P.S. The time delay will be about 5 minutes.
Since there is essentially an unknown delay between the time you send out an AJAX request and the time you receive a complete response for it, an oftentimes more elegant approach is to start the next AJAX call a fixed amount of time after the prior one finishes. This way, you can also ensure that your calls don't overlap.
var set_delay = 5000,
callout = function () {
$.ajax({
/* blah */
})
.done(function (response) {
// update the page
})
.always(function () {
setTimeout(callout, set_delay);
});
};
// initial call
callout();
Cron is run on the serverside and you are using HTML and AJAX, so you should solve this issue in Javascript :-)
By using something like setInterval you can keep executing a function, your case might be something like polling a url via AJAX:
function updatePage(){
// perform AJAX request
}
setInterval(updatePage, 5000);
Depending on your rails version you may be able to use periodically_call_remote, otherwise you'll need the jquery alternative that #Bitterzoet described.
More info in this question.
You can send ajax request in four second like this:
setInterval(get_news, 4000);
function get_news(){
$.ajax('/dashboards/get_news', {
type: 'POST',
success: function(result) {
if(result > 0){
$('#div_1').text("See "+result+" new messages");
$('#div_1').show();
}
else{
$('#div_1').css('display', 'none');
}
},
error: function() {
// alert("Error")
}
});
}
Are you using jquery? If so, you can implement this method:
// first, you need asing a callback timer
var timeout = 300; //milliseconds
// this method contain your ajax request
function ajaxRequest() { //function to ajax request
$.ajax({
url: "/url/to/request/"
}).done(function(data) {
alert("response is: " + data);
});
}
$(document).on("ready", function(){
//this method will be called every 300 milliseconds
setInterval(ajaxRequest, timeout);
});