1

I am doing api call when user enter 6 digit pincode in this condition city and state textfield autofill according to pincode.

My problem is that if I enter 6 digit pincode than it called api but while I edit text box(doing nothing just press arrow key and other key but textfield data is same means no edit) it is calling api every time if i press any button.

So I need to stop api call every time if i m not going to edit pincode

        var pin = $("input[name='postcode']").val();
        var remText = pin.replace(/ /g, "");
        var chk_pin = /^[0-9\s]*$/.test(remText);
        console.log(chk_pin + ' ' + chk_pin.length);
        openLoader();
        $("input[name='city']").val('');
        $("select[name='id_state']").val('');

            if(remText.length==6 && chk_pin){
                getbypostcode(pin);
            } else {
                $('#pincode-err1').remove();
                $('#pincode-err2').remove();
                $('#pincode-err3').remove();
                $(".postcode").append("<span id='pincode-err2' style='color:    #FF8C00'>" + checkPin + "</span>");
                closeLoader();
            }
    });
Sachin Sharma
  • 51
  • 1
  • 7

2 Answers2

1

if you want to check whether text changed or not just put the last value of text in a global var then check new val with that like this

if(lastPinVal != pin){
 lastPinVal = pin;
do ajax
}else{
do nothing
}
Sachin Sharma
  • 51
  • 1
  • 7
Babak Asadzadeh
  • 1,207
  • 1
  • 11
  • 21
  • This is only for Enter key but i need to stop for all key. See what happened I entered 6 digit pincode than it call api ok after that my cursor is in the same textField in that time i am pressing arrow key and other key also but value is same means not edited in this condition I need to stop api call – Sachin Sharma Sep 26 '19 at 11:57
0

you can use global variable to store instance of that ajax request and using that instance you can abort that ongoing ajax request anytime by using .abort() method. for more information refer this link

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
       alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()
Dhaval Pankhaniya
  • 1,996
  • 1
  • 15
  • 26