I have been attempting to integrate jQuery hovercard (http://designwithpc.com/Plugins/Hovercard) with our web application. We need it to display HTML received from an AJAX page when hovering over a username link identified with the data attribute data-toggle="user".
This is our code so far...
$('a[data-toggle="user"]').hovercard({
detailsHTML: 'Loading user details...',
width: 350,
cardImgSrc: 'http://ejohn.org/files/short.sm.jpg', //Dummy URL for now
onHoverIn: function() {
// set your twitter id
var user = 'jeresig';
$.ajax({
url: '/components/users/_hovercards/user-hovercard.php',
type: 'GET',
dataType: 'text',
beforeSend: function() {
$(this).text("Loading...");
},
success: function(data) {
$(this).empty();
$(this).text(data);
},
complete: function() {
},
error: function() {
//$(this).text("An error occured in loading the user hovercard");
$(this).text("An error occured loading the user data...");
}
});
}
});
The issue is that this does not append the HTML from the AJAX page to the hovercard. I have tried a few changes to diagnose the fault and when I explicitly call the $(this) value and attempt to manually change it outside the AJAX lines to test appending the data manually I wind up replacing the link data itself with the manually appended html and the hovercard does not display.
I have used the global selector in a few spots in my code to apply events to all elements with a particular data-toggle value and use the $(this) selector with no issue but in this instance I am having issues.
Thanks in advance.
This is because you $(this)
is not the same as $('a[data-toggle="user"]')
within the $.ajax
call. Instead, the $(this)
refers to the AJAX object, which will not do anything.
Here's a modified solution from this answer:
$('a[data-toggle="user"]').hovercard({
...
var elem = $(this);
$.ajax( ...
success: function(data) {
elem.empty();
elem.text(data);
} ...
error: function() {
elem.text("An error occured loading the user data...");
}
});
}
});
You are so close! The only change you need to make is to use:
.html('html');
or
.append('html');
In your SUCCESS setting within your ajax call definition!
Note that this will load HTML into the DOM as well as execute any <script>
tags in your Ajax response! I've done this a lot in applications I've written. Let me know if you have any questions!
You can find more information here:
.html() --- http://api.jquery.com/html/
.append() --- http://api.jquery.com/append/