$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval();
},
succes: function(data){
..................
}
})
So I am trying to end the infinite loop my code is spawning as soon as my ajax call is being done. It now phones pretty much every second to my file to get results, which i want to stop as soon as my ajax call is completed.
I am not sure how to approach this, since if i assign a variable to the setInterval (being it in the function of the beforeSend itself, or outside of the AJAX call), it either wont see the variable, or my variable is empty. I think I am approaching this wrong. Can I check within the beforeSend if the AJAX call is complete to end the loop?
you can store your interval as a global variable and clear it when you need it. like so:
let interval;
$.ajax({
url: vars.url,
type: "post",
data: r,
async: true,
processData: vars.process,
contentType: vars.contenttype,
beforeSend: function(){
if(vars.loadbar == 'true'){
interval = setInterval(function () {
$.getJSON(domain + '/core/files/results.json', function (data) {
console.log(data);
})
}, 1000);
}
},
complete: function(){
clearInterval(interval);
},
succes: function(data){
..................
}
}
Related
I'm using the jquery countdown timer plugin (http://keith-wood.name/countdown.html) to display the time. I'm calling a function to add more time on callback event 'onTick'. When the time countdowns to 00:00:00, the function will make an ajax call to add extra time. It's working fine but every time the timer equals 00, ajax is making multiple calls (>15). How can I make it to send just one call? I tried doing async: false but still it's making multiple calls. Thank you.
$(this).countdown({ until: time, format: 'HMS', onTick: addExtraTime });
function addExtraTime() {
if ($.countdown.periodsToSeconds(periods) === 00) {
var postValue = { ID: id }
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "#Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
});
ajaxLoading = false;
}
}
}
You have a variable, ajaxLoading, that you use to determine if an Ajax request is in flight but you set it to false immediately after calling $.ajax() instead of when you get a response. Set it to false inside your success and error handlers instead.
You're setting ajaxLoading = false; even when the ajax request is still being done, set it to false after the request is completed
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "#Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
complete: function(){
ajaxLoading = false;
}
});
//ajaxLoading = false;
}
I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.
(function poll() {
$.ajax({
url: "/Home/Tail", success: function (data) {
console.log(data);
},
data: { datetime: getISODateTime(new Date()) },
dataType: "json",
timeout: 30000
});
})();
I have the above code, i am doing long polling to an endpoint.
However, it is too fast. Isnt it supposed to do it every timeout seconds?
However, it is too fast. Isnt it supposed to do it every timeout
seconds?
timeout property here will only timeout the call and then fire the error. If you find it too fast, you must be doing something else besides the code posted above.
In order to do a long-polling one way could be to use Javascript setTimeout when you receive a response. Also, in such cases you should have an abort figured out somewhere.
For example (this will poll every 3 seconds):
<button id="start">Start</button>
<button id="stop">Stop</button>
var timer;
function poll() {
$.ajax({
url: "/echo/json/", success: function (data) {
console.log(data);
timer = setTimeout(poll, 3000);
},
data: { datetime: new Date()},
dataType: "json",
timeout: 30000
});
};
$("#start").on("click", function() { console.log("started.."); poll(); });
$("#stop").on("click", function() { console.log("stopped.."); clearTimeout(timer); });
Fiddle: http://jsfiddle.net/abhitalks/rf0uaaLj/
You could use the timeout setting in the ajax options like this:
(function poll() {
$.ajax({
url: "/Home/Tail", success: function (data) {
console.log(data);
},
timeout: 30000,
data: { datetime: getISODateTime(new Date()) },
dataType: "json"
});
})();
Read all about the ajax options here
I want to start an ajax loop with GET-requests to check statuses from my controller. Once the loop is started i want to start a file download by changing window.location.
However i get no console.logs from this code, why?
function getExcelIKT() {
setInterval(function () {
$.ajax({
type: 'GET',
url: getDownloadCSVForIKTStatusUrl,
dataType: 'json',
async: 'true',
success: function (DownloadCSVForIKTStatus) {
console.log(DownloadCSVForIKTStatus);
}
});
}, 3000);
window.location = downloadExcelUrlIKT;
}
function getExcelIKT() {
setInterval(function () {
$.ajax({
type: 'GET',
url: getDownloadCSVForIKTStatusUrl,
dataType: 'json',
async: 'true',
success: function (DownloadCSVForIKTStatus) {
console.log(DownloadCSVForIKTStatus);
if (false) { //change to some conditions
window.location = downloadExcelUrlIKT;
}
}
});
}, 3000);
}
Just change if (false) { to something if (DownloadCSVForIKTStatus.success) {
Why don't you see console.logs? Because setInterval and $.ajax functions are asynchronous. For example
setTimeout(function () {
console.log(1);
setTimeout(function () {
console.log(2);
},0);
console.log(3);
},0);
console.log(4);
Result will be 4 1 3 2. (I use setTimeout instead of setInterval, which is also asynchronous even with timeout of 0 seconds)
I have the following code:
$('#DoButton').click(function (event) {
event.preventDefault();
$("input:checked").each(function () {
var id = $(this).attr("id");
$("#rdy_msg").text("Starting" + id);
doAction(id);
});
});
function doAction(id) {
var parms = { Id: id };
$.ajax({
type: "POST",
traditional: true,
url: '/adminTask/doAction',
async: false,
data: parms,
dataType: "json",
success: function (data) {
$("#rdy_msg").text("Completed: " + id);
},
error: function () {
var cdefg = data;
}
});
}
When the button is clicked it checks the form and for each checked input it calls doAction() which then calls an Ajax function. I would like to make it all synchronous with a 2 second delay between the completion of one call and the running of the next. The delay is to give the user time to see that the last action has completed.
By setting async=false will that really make the ajax function wait?
How can I add a 2 second wait after the Ajax has run and before the next call to doAction?
There is option in jQuery to set the ajax function synchronous
$.ajaxSetup({
async: false
});
To make the function to wait you can use .delay()
Try the solution of this question also.
Try to do it using recursion
$('#DoButton').click(function (event) {
event.preventDefault();
doAction( $("input:checked").toArray().reverse() );
});
function doAction(arr) {
if( arr.length == 0 ) return;
var id = arr.pop().id;
$("#rdy_msg").text("Starting" + id);
$.ajax({
type: "POST",
traditional: true,
url: '/adminTask/doAction',
async: false,
data: { Id: id },
dataType: "json",
success: function (data) {
$("#rdy_msg").text("Completed: " + id);
setTimeout(function(){ doAction(arr); }, 2000);
},
error: function () {
var cdefg = data;
$("#rdy_msg").text("Error: " + id);
setTimeout(function(){ doAction(arr); }, 2000);
}
});
}
Use setTimeout for the AJAX call doAction.