abort or readyState is undefined with Ajax - javascript

i got that error with bellow code;
Uncaught TypeError: Cannot read property 'readyState' of undefined
And when i try delete the readyState for see the whats happend that i got that error;
TypeError: Cannot read property 'abort' of undefined
get: function () {
var ajaxReq = $.ajax({
type: 'GET',
url: data.url,
dataType: "json",
success: function (response, status) {
callback(response);
},
beforeSend: function () {
if (ajaxReq != 'ToCancelPrevReq' && ajaxReq.readyState < 4) {
ajaxReq.abort();
}
}
});
}
That function working with keypress;
keypress: function () {
setTimeout(function () {
if ($(OnePageCheckout.Selector.CardNumber).val().length == 7) {
$(".payment-installment-container").removeClass("d-none");
InvUtility.Loader.Open();
var model = {
value: $(OnePageCheckout.Selector.CardNumber).val()
}
OnePageCheckout.OnCardNumberUpdate.event(model);
}
}, 1000)
OnePageCheckout.OnCardNumberUpdate.init();
},
The keypress is send request so many times and i want to sure that the sucsess process working just one time

You should declare ajaxReq before you call $.ajax(). Then just check if it's not empty before trying to use it, rather than using a special value like ToCancelPrevReq.
And once you get a successful response, you can reset it so the next keypress can make the AJAX request again.
var ajaxReq;
...
if (ajaxReq && ajaxReq.readyState < 4) {
ajaxReq.abort();
}
$.ajax({
type: 'GET',
url: data.url,
dataType: "json",
success: function(response, status) {
ajaxReq = null;
callback(response);
}
});

this code solved my problem
I defined the variable outside of the get function. If I define it inside the GET function, it is taken as a new transaction because it is emptied every time. So defining it outside of the relevant function gave the correct result
var jqxhr = {abort: function () {}};
get: function(){
jqxhr.abort();
var ajaxReq = $.ajax({
type: 'GET',
url: data.url,
dataType: "json",
success: function (response, status) {
callback(response);
}
});
}

Related

Getting Data from Ajax request displayed

I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});

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

Trouble reading from json file in Javascript

I know next to nothing about ajax and json. Right now I'm trying to read the data from dealerData.json into my MVVM viewModel and 'data' keeps coming back as undefined.
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
success: function (data) {
obj = JSON.parse(data);
}
});
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
});
Try like this:
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
})
.done(function (data) {
obj = JSON.parse(data);
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
});
})
ko.applyBindings(DealerNumberLotNumberViewModel(obj)); - this should go inside the callback method though like this -
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
success: function (data) {
obj = JSON.parse(data);
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
}
});
Because obj is undefined till the callback method "success" actually assigns it something. and ko.applyBinding method should execute once obj is defined. Hence, it should go inside the callback method.
Also, it is a good idea to always have a failure callback method, just so that any failure doesn't go uncaught.
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
success: function (data) {
obj = JSON.parse(data);
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
},
error: function(args) {
console.log('error occured: '+ args);
}
});
Hope, this helps

How to return the result of an ajax call as the return value of a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a class with a method which gets something from the server. I'm trying to find a way to be able to return "something" from the function that later "becomes" the data which the server responds with. Here's the idea:
#find: (id) ->
response = THING
$.ajax
type: 'GET'
url: "#{this::url}/#{id}"
dataType: 'json'
success: (data) =>
response.become #init(data)
error: (xhr, status, error) ->
response.reject error
response
The use of this method would look like this:
myBlah = Product.find(1)
I recognize that this is similar to the concept of a promise, which I'm only vaguely familiar with. Is there something I'm missing here?
Try setting the 'async' option of $.ajax to false. If at all possible try working with callbacks. I've added a solution for both scenarios.
var Product = {};
Product.find = function(id) {
var response;
$.ajax({
async: false,
type: 'GET',
url: "/product/" + id,
dataType: 'json',
success: function(data) {
response = new ProductModel(data);
},
error: function(xhr, status, error) {
response = null;
}
});
return response;
};
var myProduct = Product.find(1);
if (myProduct != null) {
myProduct.getPrice();
}
Here's how the above code would work using a callback function.
var Product = {};
Product.find = function(id, callback) {
$.ajax({
type: 'GET',
url: "/product/" + id,
dataType: 'json',
success: function(data) {
var response = new ProductModel(data);
if (typeof callback != 'undefined') {
callback(response);
}
},
error: function(xhr, status, error) {
if (typeof callback != 'undefined') {
callback(null);
}
}
});
};
Product.find(1, function(myProduct) {
if (myProduct != null) {
myProduct.getPrice();
}
});

IE not calling $.ajaxSetup

The following call works great in every browser but IE. $.ajaxSetup doesn't get recognized. The error and complete functions won't be called unless I add them directly into the $.ajax call.
Any idea why?
function setupAjaxCalls() {
$.ajaxSetup({
type: 'GET',
dataType: "jsonp",
contentType: "application/json",
data: {
deviceIdentifier: deviceIdentifier,
deviceType: deviceType,
memberId: loggedInMemberId,
authToken: authToken,
cache: false,
responseFormat: 1
},
error: function (x, e) {
defaultError(x, e);
},
complete: function () {
apiCallInProgress = 'false';
//alert('complete!');
}
});
}
function logInForm(memLogin, memPassword, callback) {
apiCallInProgress = 'true';
$.ajax({
type: 'POST',
dataType: "json",
url: baseApiUrl + '/MembershipService/AuthLoginSecure',
data: {
login: memLogin,
password: memPassword,
responseFormat: 0
},
success: function (data) {
if (data.Success == false) {
apiError(data);
} else {
loggedInMemberId = data.Member.Id;
authToken = data.Token;
if (typeof (callback) != "undefined" || callback) {
callback(data);
}
}
}
});
}
Straight from the documentation:
http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective global Ajax event
handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(),
.ajaxSend()—rather than within the options object for $.ajaxSetup().
You should move the error and complete properties into their own methods. :) Or, you can just put them into the $.ajax method. Whatever works best for your preferred code pattern!

Categories

Resources