1

I am trying to cancel all remaining AJAX requests if the length of an input field is empty. However, I am seeing this error:

Uncaught TypeError: Cannot read property 'abort' of undefined

$("input#enter").keyup(function() {
    if(this.value.length < 1) {
        $("#display").empty();
        request.abort(); // <--- this line
    }else{ 
        var request = $.ajax({
            type: "POST",
            url: "getdata.php",
            data: "title=" + this.value,
            success: function(data) {
                $("#display").empty(); 
                $("#display").html(data);
            }
        });
    } 
});

This is where I saw a similar example and they used request.abort(): Stop all active ajax requests in jQuery

The Codesee
  • 3,714
  • 5
  • 38
  • 78

1 Answers1

0

Your issue is due to the scope of the request variable. You need to declare it outside of the handler:

var request;

$("input#enter").keyup(function() {
  var $display = $('#display');
  if (this.value.trim().length < 1) {
    $display.empty();
    request && request.abort();
  } else {
    request = $.ajax({
      type: "POST",
      url: "getdata.php",
      data: { title: this.value.trim() },
      success: function(data) {
        $display.html(data);
      }
    });
  }
});

Note that I amended the JS code slightly, as you don't need to call empty() if you're overwriting the html() anyway.

Also, assuming this is a kind of filtering system, you may want to consider using abort() on request in all instances, as if a new key has been pressed then the previous request is no longer relevant to the results and can be ended - something like this:

var request;

$("input#enter").keyup(function() {
  var $display = $('#display');
  request && request.abort(); // always abort the previous request, if there was one

  if (this.value.trim().length > 0) {
    request = $.ajax({
      type: "POST",
      url: "getdata.php",
      data: { title: this.value.trim() },
      success: function(data) {
        $display.html(data);
      }
    });
  }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339