Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting data-content and displaying popover

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!

like image 756
licorna Avatar asked Nov 09 '11 15:11

licorna


2 Answers

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.

like image 88
a paid nerd Avatar answered Oct 11 '22 14:10

a paid nerd


In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:

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');
         }
    });
}
like image 42
Yannis Avatar answered Oct 11 '22 13:10

Yannis