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);
}
});
}
}
});
Related
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 am new to Ajax and want to make an Ajax Request to a view function in Django with jQuery, but I am stuck.
I started with a simple example to check if it works
var button = $('.any_button');
$(button).click(function() {
var button_value = $(this).val();
$.ajax({
type: "POST",
url: "/url-path/to-my/view-function/",
dataType: "json",
data: { "button_value": button_value },
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
});
I have inserted from https://docs.djangoproject.com/en/1.11/ref/csrf/
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
my view function:
from django.http import JsonResponse
def button_check(request):
data = {"message": "Message"}
return JsonResponse(data)
My url path refers to views.button_check
I get the beforeSend alert and the error alert, but I expect the success alert
What did I miss? Unfortunately I am not able to go ahead.
in jquery try like this,
$.ajax({
type: "POST",
url: "/button_check/",
method: "POST",
data: { "button_value": button_value },
contentType: "application/json",
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
url should be,
url(r'button_check/', 'views.button_check'),
if your request is "POST" or specific try,
def button_check(request):
if request.method == "POST":
data = {"message": "Message"}
return JsonResponse(data)
Your ajax setup is overwritten by values you pass to jQuery.ajax:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
//this will never happen because it is overridden later
alert("you will never see this.");
}
});
$.ajax({
type: "GET",
url: "/index.html",
beforeSend: function () {
console.log("another before send");
},
})
.then(x => console.log("success:",x))
.then(undefined,reject => console.error(reject));
This means you won't authenticate and get the csrf token missing.
As you told in comments; remove the boforesend in $.ajax
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);
})();
I have a collapsible element wherein an ajax is requested when the collapsible is opened. However, I also want to stop the ajax request before the collapsible is closed.
$(".collapse").on('show.bs.collapse', function(e) {
$.ajax
({
type: "GET",
url: "check_active_operator.php",
cache: false,
success: function(r)
{
if(r==1){
//Operator is available
}else if(r==0){
//No operator available
}
}
});
});
$(".collapse").on('hide.bs.collapse', function(e) {
// STOP AJAX REQUEST
});
NOTE: I also have this ajax request on check_active_operator.php. That request must be aborted as well if the collapsible is closed. As of now, it is still running when the collapsible is closed.
function getMessages(){
var getchatroomid = $.trim($("#chatroomid").val());
$.ajax
({
type: "POST",
url: "messages.php",
data: {getchatroomid},
cache: false,
success: function(data)
{
$(".chatMessages").html(data);
}
});
}
setInterval(function(){
getMessages();
var c = $('.chatMessages');
c.scrollTop(c.prop("scrollHeight")); //scroll down
}, 1000); //half a second
You can use abort function like this
var xhr;
$(".collapse").on('show.bs.collapse', function(e) {
xhr = $.ajax
({
type: "GET",
url: "check_active_operator.php",
cache: false,
success: function(r)
{
if(r==1){
//Operator is available
}else if(r==0){
//No operator available
}
}
});
});
$(".collapse").on('hide.bs.collapse', function(e) {
xhr.abort();
});
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.