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


i'm making $.ajax call, , following code not work intended. 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, able working adding alias $(this) before entering 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 element being clicked, accessing via $("#id") isn't option.

is there more standardized approach accessing $(this) existed before entering success function or way work fine?

the way have fine. default this in jquery ajax callbacks ajax settings object (you can set via $.ajaxsettings). $.ajax has context property can set:

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

then use $(this) expected, find reassignment of this easier understand. may want pick better variable name old_this, though.


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -