Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  94] [ 5]  / answers: 1 / hits: 26352  / 13 Years ago, wed, november 9, 2011, 12:00:00

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:



$('.myclass').popover({trigger: manual, html:true});
$('.myclass').click(get_data_for_popover_and_display);


and the function for retrieving data is:



get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}


What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.



Any idea why is happening this? Thanks!


More From » jquery

 Answers
37

In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().



Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.



You can solve this by keeping a reference to this by assigning it to a variable:



get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}


Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.


[#89223] Tuesday, November 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tajo

Total Points: 415
Total Questions: 124
Total Answers: 103

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
;