Customizing data content and displaying popover

I am trying to get data from a resource using jquery ajax, and then I am trying to use this data to populate a popup, for example:

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

and function for receiving data:

 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 happens is that the popover is not displayed when I click, but if I visit the item later, it will display a popover, but without content ( data-content attribute). If I put alert() in the success callback, it will display the returned data.

Any idea why this is happening? Thank!

+3
javascript jquery twitter-bootstrap
Nov 09 '11 at 15:31
source share
2 answers

In its callback, this no longer bound to the same value as the rest of get_data_for_popover_and_display() .

Do not worry! The keyword this is hairy; misinterpretation of its meaning is a common JavaScript error.

You can solve this problem by saving the link 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 can write var that = this; and use $(that) everywhere. More solutions and background here .

+11
Nov 09 '11 at 15:47
source share

In addition to the answer above, do not forget that according to $. ajax () documentation you can use context to achieve the same result without declaring an additional variable:

 get_data_for_popover_and_display = function() { $.ajax({ type: 'GET', url: '/myresource', data: $(this).attr('alt'), dataType: 'html', context: this, success: function(data) { $(this).attr('data-content', data); $(this).popover('show'); } }); } 
+6
Aug 31 '12 at 10:13
source share



All Articles