Ajax string comparison - javascript

I have a basic ajax function
setInterval(function() {
var action = '';
var status = '';
$('#php-data').load('../Data/Dashboard.Data.php');
$.ajax({type: 'POST', url: 'Data/Dashboard.Image.php', data: { json: action }, dataType: 'json' }).done(function(data) {
console.log('Ajax Data: ' + data);
status = JSON.parse(data);
**if(status === 'false') {**
console.log("script is NOT running");
drawPieChart();
} else {
console.log("script is running");
$('#php-image').load('../Data/Dashboard.Image.php'); //todo only load this is the ajax returned from Dashboard.image.php is true
}
});
}, 5000);
basically the only thing my ajax returns is "false" so when I compare status to false it should be true and drawPieChart(); but instead it always runs the jquery load() function even though my ajax data is returning false every single time.
ive also tried this:
setInterval(function() {
var action = '';
var status = '';
$('#php-data').load('../Data/Dashboard.Data.php');
$.ajax({type: 'POST', url: 'Data/Dashboard.Image.php', data: { json: action }, dataType: 'json' }).done(function(data) {
console.log('Ajax Data: ' + data);
status = data;
**if(status === 'false') {**
console.log("script is NOT running");
drawPieChart();
} else {
console.log("script is running");
$('#php-image').load('../Data/Dashboard.Image.php'); //todo only load this is the ajax returned from Dashboard.image.php is true
}
});
}, 5000);
and this :
setInterval(function() {
var action = '';
$('#php-data').load('../Data/Dashboard.Data.php');
$.ajax({type: 'POST', url: 'Data/Dashboard.Image.php', data: { json: action }, dataType: 'json' }).done(function(data) {
console.log('Ajax Data: ' + data);
**if(data == 'false') {**
console.log("script is NOT running");
drawPieChart();
} else {
console.log("script is running");
$('#php-image').load('../Data/Dashboard.Image.php'); //todo only load this is the ajax returned from Dashboard.image.php is true
}
});
}, 5000);

if(status === 'false')
This suggests a string. use this instead:
if(status == false)
you could simplify it even further like so:
if(!status)

Related

The Function App/GetSPANList returns 401 error on server. C# asp.net

The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}

Ajax. On Ajax success call same ajax function one more time

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);
}
}
});
}

How to make an Django Ajax Request with jQuery?

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

Execute Ajax queries one after one with Jquery

I'm trying to execute ajax post requests one after one and stop only when the result is something like "done". But I can't figure out why it is not looping...I get a json answer but I can't do anything with success response.
My code so far:
var index = 0;
function crawler(textarea) {
index = 0;
if(url != ''){
if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(url)){
execute_queue(index);
}
}
};
function execute_queue(index)
{
url = strip_tags($('#input-website').val().trim());
folders = strip_tags($('#excluded-folders').val().trim());
$.ajax( {
url: 'xxx',
cache: false,
type : 'POST',
async: false,
data: {url:url, folders:folders, current:index},
success: function(response)
{
index++;
execute_queue(index);
}
});
};
Thanks in advance for your help.
You should check if the request failed, this is straight from the JQuery manaual:
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
More info found here, success will not be called if the URL responds with an error.
UPDATE:
I think your code should look something like this:
var index = 0;
function crawler(textarea) {
index = 0;
if(url != ''){
if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(url)){
execute_queue(index);
}
}
};
function execute_queue(index)
{
url = strip_tags($('#input-website').val().trim());
folders = strip_tags($('#excluded-folders').val().trim());
$.ajax( {
url: 'xxx',
cache: false,
type : 'POST',
data: {url:url, folders:folders, current:index},
success: function(response)
{
index++;
execute_queue(index);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + " : " + errorThrown);
}
});
};

how to stop ajax request if another request exist

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);
}
});
}
}
});

Categories

Resources