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);
}
}
});
}
Related
Am trying to get data from ajax if success data is empty need to call same ajax until ajax success data is returned.
Can some one help me to call ajax ever 2 sec until ajax returns data.
this.submitPax = function() {
function getCityName() {
var country = 1;
//var ajaxUrl = "<?php echo WEB_URL_ADMIN; ?>checkdriverstatus";
tjq.ajax({
url: baseUrlIs + "checkdriverstatus",
dataType: 'json',
type: 'post',
data: { "countryID": country },
success: function(response, textStatus, request) {
//alert(response);
if (response != '') {
tjq("div#divLoadingSeat").removeClass('show');
} else {
alert('Waiting for driver to accept job');
//setTimeout(function(){getCityName();}, 1000);
tjq("div#divLoadingSeat").addClass('show');
return false;
}
},
});
}
}
I am calling Ajax when user click the button. When calling ajax it will check the data with textbox whether the textbox value is already exist or not. If exist, then it should not return false, if the record is not found in database, jquery button should return true let it to save on database through server side.
Note:
My Ajax code is working. But when I the is exist and set return false this statement is not execute.
Here is my code:
$('#btnSaveFile').click(function () {
var fileNames = $('#txtFileName').val();
var flags = 'test';
alert('test='+flags);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'post',
async:false,
contentType: 'application/json',
data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
dataType: 'json',
success: function (data) {
if (data.d === 'dataExist') {
// it execute this loop, but after it execute it's going to server
$('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
return false;
}
else {
return true;
}
},
error: function (error) {
alert('Please Call Administrator');
}
});
});
I found result myself.
Ajax is an Asynchronous. We cannot do return false when the result is success.
So I declare one variable outside of ajax and with the certain condition in success I set return false in outside of ajax code
This is my Jquery code
$('#btnSaveFile').click(function () {
var fileNames = $('#txtFileName').val();
var flag = 'returnTrue';
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'post',
async: false,
contentType: 'application/json',
data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
dataType: 'json',
success: function (data) {
if (data.d === 'dataExist') {
flag = 'returnFalse';
$('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
}
else {
alert('else');
return true;
}
},
error: function (error) {
alert('Please Call Administrator');
}
});
if (flag === 'returnFalse') {
return false;
}
});
Below if my code...
$(document).ready(function() {
var counter=0;
$.ajax({
url: "http://www.test.com:1234/testService",
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data
})
.done(function(data) {
console.log(data);
})
.fail(function(errMsg) {
console.log(errMsg);
counter++;
console.log(counter);
if(counter <=3){
$.ajax(this);
}
else {
alert("Three times failed");
}
});
});
Run this code will get correct data from API.
However, if I remove the "e" in the end of api url, the API will failed and what I want is to retry again until failed three times and alert some message.
But this code is not working.
What should I do?
What you can do is create a function that makes the ajax request and on failure invoke the function again.
$(document).ready(function () {
var counter = 0;
function apiCall() {
$.ajax({
url: "http://www.asiavista.com.tw:9595/ccplapi/service.svc/CheckService",
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ClientType: 1})
})
.done(function (data) {
console.log(data);
})
.fail(function (errMsg) {
console.log(errMsg);
counter++;
console.log(counter);
if (counter <= 3) {
apiCall(); // Try api call again
} else {
alert("Three times failed");
}
});
}
apiCall(); // Trigger the first api call
});
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 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.