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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With