javascriptjqueryajaxabortreadystate

abort or readyState is undefined with Ajax


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


Solution

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