I want to implement AJAX polling mentioned in this answer. Now I want to break out of polling when server return particular data value. How to do that?
Try something like this (where you change the condition to set continuePolling false to whatever you need):
(function poll() {
var continuePolling = true;
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
if (data.length == 0)
{
continuePolling = false;
}
},
dataType: "json",
complete: function() { if (continuePolling) { poll(); }),
timeout: 2000
})
}, 5000);
})();
Related
$.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){
..................
}
}
This is what i tried.
tjq.ajax({
type: 'POST',
url: '<?php echo base_url();?>getCmsHotel?t=<?php echo $traceId;?>',
dataType: 'JSON',
encoding:"UTF-8",
contentType: "application/json",
traditional: true,
async: true,
error: function (request, error) {
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
},
success: function (data) {
//alert(data.status);
if(data.status == 'FAILURE'){
//searchresults = data;
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
}else if(data.status == 'SUCCESS'){
var recalajx = '2';
if(recalajx =='2' && recalajx!=3){
recalajx ='3';
tjq.ajax(this);
}
alert(recalajx);
tjq('.searchresultsDiv').remove();
hotelsresults = data;
//hotelssearchObj.hotelsResults(data);
gblStartCount = 1;
gblHotelData = tjq.extend(true, {}, data);
gblHotelDisplayData = tjq.extend(true, {}, data);
hotelssearchObj.hotelsResults(gblHotelDisplayData);
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
tjq("div#divLoading").removeClass('show');
}
}
});
This code calling multiple times. Am trying to call tjq.ajax(this); only once after 1st ajax SUCCESS.
when tried to alert getting 3 but still axaj calling for multi times.
How to stop this can some help!
One solution is to put the Ajax call in a function, and check how many times it has been called with a counter. If the counter is less than 2, call the function again.
here's an example:
ajaxCall();
function ajaxCall(counter = 0) {
$.ajax({
type: 'POST',
success: function() {
counter++
if (counter < 2) {
ajaxCall(counter);
}
}
});
}
i'm trying to make infinite scrolling so when scrolling i make an ajax request to the server to get data but when scrolling a multiple ajax request is made and return the same data so how can i cancel ajax request before sending if there one already exist i tried like this
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
all my code
var lock_load = '1';
var activeAjaxConnections = 1;
var PageNumber = 2;
$(window).scroll(function () {
if ((Math.ceil($(window).scrollTop() - $(window).height()) * -1) <= getHeight() + 550) {
if (lock_load === '1') {
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
alert(errorThrown);
n }
});
}
}
});
but it give an error xhr is undefined pleas any help and many thanks in advance.
Try flags
Before making ajax call set flag to true and after ajax call is made set flag to false, finally on completion of ajax request again set flag to ture
var ready = true;
$(window).scroll(function(){
if(ready == true){
ready = false;
$.ajax({
url: "/pagination",
cache: false,
success: function (response){
//response
}
}).always(function () {
ready = true; //Reset the flag here
});
}
});
use the below code, use a simple flag variable that will be set to false by the defualt, that is to say that ajax call is not occuring once if condition is met then it will set to true to say that ajax call has started, once the success: or error: call back fires the variable will be set to false so that another ajax call can be made.
startedAjax = false;
if (lock_load === '1') {
startedAjax = true;
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
startedAjax = false //set is false
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
startedAjax = false;
alert(errorThrown);
}
});
}
}
});
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.