Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: using $(this) inside of $.ajax success function

I'm making an $.ajax call, and the following code does not work as intended. The alert results in 'undefined'

$(document).ready( function {
  $(".elem").on("click", function(e) {

    e.preventDefault();

    $.ajax( {
      url: 'index.php',
      data: {
        'action': 'something'
      },
      success: function() {
        alert($(this).data("foobar"));
      }
    });
  });
)};

However, I was able to get it working by adding an alias to $(this) before entering the ajax function.

$(document).ready( function {
  $(".elem").on("click", function(e) {

    var old_this = $(this);

    e.preventDefault();

    $.ajax( {
      url: 'index.php',
      data: {
        'action': 'something'
      },
      success: function() {
        alert(old_this.data("foobar"));
      }
    });
  });
)};

I can't assign unique IDs to the element being clicked, so accessing it via $("#id") isn't an option.

Is there a more standardized approach to accessing the $(this) that existed before entering the success function or does this way work just fine?

like image 853
OnNIX Avatar asked Feb 12 '23 20:02

OnNIX


1 Answers

The way that you have it is just fine. By default this in jQuery ajax callbacks is the ajax settings object (you can set via $.ajaxSettings). $.ajax also has a context property that you can set:

$.ajax({
    url: url,
    data: data,
    context: this,
    success: success
});

Then you could use $(this) as expected, but personally I find the reassignment of this easier to understand. You may want to pick a better variable name than old_this, though.

like image 132
Explosion Pills Avatar answered Feb 15 '23 11:02

Explosion Pills