Cannot use 'in' operator to search for 'sth' in undefined

Here is my code:

.
.
keydown: function(ev) {

    clearTimeout( $(this).data('timer') );
    if ( 'abort' in $(this).data('xhr') ) $(this).data('xhr').abort();       // error here
    var xhr, timer = setTimeout(function() {
        xhr = $.ajax({
            url :  '/files/tags_autocomplete.php',
            dataType : 'JSON',
            success : function (tags) {
            $("ul").html(tags.output);
            }
        });
    }, 500);

    $(this).data({timer : timer, xhr : xhr});
}
.
.

As I said, the third line causes this error:

Uncaught TypeError: Cannot use "in" operator to search for "abort" in undefined

How can i fix this?

0
source share
3 answers

Edit:

if ('abort' in $(this).data('xhr') ) $(this).data('xhr').abort(); 

at

if ($(this).data('xhr') && $(this).data('xhr').abort) {
  $(this).data('xhr').abort(); 
}

The problem was simply checking if the object has an xhrelement. By default, it does not exist, therefore it undefined, and you asked the JS engine to find the element in the undefinedinformation causing the error.

, , , .data('xhr'), JS undefined false, , data('xhr') abort.

, , -, AJAX, XHR :

if($(this).data('timer')) {
  clearTimeout($(this).data('timer'));
}

var timer = setTimeout(function() {
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
          $("ul").html(tags.output);
        }
    });
}, 500);

$(this).data('timer', timer);

( ):

if(window.autocompleteTimer) {
  clearTimeout(window.autocompleteTimer);
}

window.autocompleteTimer = setTimeout(function() {
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
          $("ul").html(tags.output);
        }
    });
}, 500);
+2

, undefined . data() , .

var xhr = $(this).data('xhr');
if(typeof xhr !== 'undefined' && xhr.abort) {
    // code goes here
}

if 4 .

+2

The problem is that if the user re-enters the data before 500 ms has passed, it $(this).data('xhr')will be undefined, as he is not yet configured for an ajax request.

Since we cannot use the operator inon undefined, only on objects, the correct decision is how to clear the timeout and interrupt any requests waiting for a request, just check whether the $(this).data('xhr')object is installed and before checking if it has a propertyabort

keydown: function(ev) {
  var self = $(this);

  clearTimeout(self.data('timer'));

  if (typeof self.data('xhr') === 'object' && 'abort' in self.data('xhr')) {
    self.data('xhr').abort();
  }

  var timer = setTimeout(function() {
    self.data('xhr', $.ajax({
      url: '/files/tags_autocomplete.php',
      dataType: 'JSON',
      success: function(tags) {
        $("ul").html(tags.output);
      }
    }));
  }, 500);

  self.data('timer', timer);
+1
source

Source: https://habr.com/ru/post/1655523/


All Articles