How to abort ajax request - javascript

In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}

var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()

var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.

Related

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

how to push values to an array outside the loop from a nested ajax call with javascript

I have a for loop which loops about 16 times and each time it loops i want a value to be pushed to the array i declared outside the loop and the array is pushed from a nested ajax call in the loop. i wrote an if condition that if the loop reaches 16 times it should alert all the contents of the array at once but i'm getting an empty value
var comment = [];
for (var i = 0; i < jsons.length; i++){
var obj = jsons[i];
if( i == jsons.length - 1 )
{
alert(comment);
break;
}
var idno = '';
idno = obj.IDNO;
var amount = obj.AMOUNT;
(function(i)
{
$.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoauth: obj.IDNO, amount: amount, },
dataType: 'json',
cache: false,
success: function(result){
if(result[0].idno == '')
{
alert(result[0].idno + " " + result[0].amount);
}
else if(result[0].idno != ''){
var idnoresult = result[0].idno;
var amountresult = result[0].amount;
$.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoinsert: idnoresult, amountinsert: amountresult},
cache: false,
success: function(gg){
if(gg != '')
{
comment[i] = gg;
}
}
});
}
}
});
})(i);
}
the updated one is still not working as expected its returning an empty array
var comment = [];
for (var i = 0; i < jsons.length; i++){
//var comments = [];
var obj = jsons[i];
/*if (typeof obj.IDNO === 'string' && obj.IDNO.length)
{
alert('good');
}
else{
alert('bad');
}*/
//alert(obj.REASON);
//console.log(obj);
//alert(obj.REASON);
if( i == jsons.length - 1 )
{
alert(comment);
break;
}
var idno = '';
idno = obj.IDNO;
var amount = obj.AMOUNT;
var jqxhr1 = $.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoauth: obj.IDNO, amount: amount, },
dataType: 'json',
});
var jqxhr2 = $.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoinsert: obj.IDNO, amountinsert: amount},
});
$.when(jqxhr1, jqxhr2).then(function(result, gg) {
//alert(result[0].idno + " " + result[0].amount);
if(result[0].idno == ''/*&& result[0].amount == '' && result[0].idnoerror != ''*/)
{
alert(result[0].idno + " " + result[0].amount);
comments.push(result);
}
else if(result[0].idno != ''/* && result[0].amount != '' && result[0].idnoerror == ''*/){
var idnoresult = result[0].idno;
var amountresult = result[0].amount;
if(gg != '')
{
comment.push(gg);
/*if( i == jsons.length - 1 )
{*/
//alert(gg);
//alert(comments);
//break;
//}
}
}
//alert(idnoresult + " " + amountresult);
// Handle both XHR objects
//alert("all complete");
});
//})(i);
}enter code here

Javascript array - element access

I have
var prosjeci = [];
var parametar = $("#parametar1").val();
Function for getting data from server:
function podatciPrethodniDan()
{
$.ajax({
type: "POST",
url: "php/getPreviousDayData.php",
dataType: "json",
data: {parametar: parametar },
success: function(data)
{
obradiPodatkePrehtodnogDana(data);
}//end of success
});//end of ajax
}
Function which fill array with data:
function obradiPodatkePrehtodnogDana(data)
{
var stanica1Prosjek = 0;
var stanica2Prosjek = 0;
var stanica3Prosjek = 0;
var stanica4Prosjek = 0;
console.log(data);
for(i=0; i<data.length; i++)
{
if(i<24)
{
stanica1Prosjek = stanica1Prosjek + parseFloat(data[i].par);
}
else if(i>=24 && i<48)
{
stanica2Prosjek += parseFloat(data[i].par);
}
else if(i>=48 && i<72)
{
stanica3Prosjek += parseFloat(data[i].par);
}
else
{
stanica4Prosjek += parseFloat(data[i].par);
}
}
prosjeci.push(stanica1Prosjek/24);
prosjeci.push(stanica2Prosjek/24);
prosjeci.push(stanica3Prosjek/24);
prosjeci.push(stanica4Prosjek/24);
}
Results of console.log(data):
(only first elment)
Array[96]
0:Object
datum:"2016-10-31"
par:"60"
stanica"1"
Call function
podatciPrethodniDan();
Print out array:
console.log(prosjeci);
console.log(prosjeci[0]);
I get all data succesfull and i fill array sucessfull but i can't to access array element.
Results of first console.log:
Array[4]
0:60.44999999999999
1:76.41666666666667
2:85.3875
3:82.47083333333335
length:4
Results of second console.log:
undefined
I cant access arrays element?

Getting type error while using Ajax call in JavaScript/jQuery [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I am getting the following error while extracting some value inside loop using jQuery. I am showing my error below.
Uncaught TypeError: Cannot read property 'no_of_optional' of undefined
I am providing my code below.
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i != 0) {
$("#questions0").val(qdata[0].questions);
$('#noofoption0').val(qdata[0].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[0]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
for (var j = 0; j < qdata[0].no_of_optional; j++) {
}
}
cnt++;
}
})
}
if (i == 1) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
}
}
})
I am getting error at this console.log('first question',qdata[i].no_of_optional); .Actually qdata is containing the two set of data(qdata[0],qdata[1]) but inside the second ajax call i is becoming 2.
Here I am expecting qdata[1].no_of_optiona inside second ajax call.
use a closure, by the time the done callback is called the for loop has finished and incremented i:-
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i == 1) {
(function(i) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
})(i);
}
}
})

Send back returned response to ajax call

I have a ajax function in index.php which calls on the page thread.php which returns a JSON response(array). I basically want to parse through that array, display it in a particular html format, take the last value of the last row of that array and send it back in the same ajax call previously mentioned. So that ajax is basically a loop.
function returnValue()
{
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
var dateposted = results[5];
}
}
}
}
});
}
The stored value dateposted needs to be sent as an input when making the ajax call. The default value of dateposted will be 0.
I am not sure if this can be done. I am open to suggestions.
You can make this a lot simpler, you don't need to use the extended GET syntax:
var returnValue = (function() {
var dateposted = 0;
return function() {
$.get("thread.php", { "lastposted": dateposted }, function(result) {
// display your chats
dateposted = result[result.length-1][5];
}, "json");
}
})();
One simple way to your problem is declaring dateposted with a default value outside the function call and use it in the loop to store to store the last value. And have a new Ajax function call. I hope this is want you want.
function returnValue()
{
var dateposted=0;
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
dateposted = results[5];
}
}
}
}
});
}

Categories

Resources