abort or readyState is undefined with Ajax

267 views Asked by At

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

2

There are 2 answers

0
Barmar On BEST ANSWER

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

0
idiltugba On

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