I’m using the following code to display a “popover” effect on my products. The content of the popover comes from Ajax. This is using Twitter Bootstrap popovers. Is it possible to make the Ajax call only once? Right now, every time I mouse over the product, the request is sent again. I’d like to tweak this code so if the content has already been fetched, use it and don’t make another request.
Thanks
$(document).ready(function(){
//Quick view boxes
var overPopup = false;
$("a[rel=popover]", '.favorites').popover({
trigger: 'manual',
placement: 'bottom',
html: true,
content: function(){
var div_id = "div-id-" + $.now();
return details_in_popup(div_id, $(this).data('product-id'));
}
}).mouseover(function (e) {
// when hovering over an element which has a popover, hide
// them all except the current one being hovered upon
$('[rel=popover]').not('[data-unique="' + $(this).data('unique') + '"]').popover('hide');
var $popover = $(this);
$popover.popover('show');
$popover.data('popover').tip().mouseenter(function () {
overPopup = true;
}).mouseleave(function () {
overPopup = false;
$popover.popover('hide');
});
}).mouseout(function (e) {
// on mouse out of button, close the related popover
// in 200 milliseconds if you're not hovering over the popover
var $popover = $(this);
setTimeout(function () {
if (!overPopup) {
$popover.popover('hide');
}
}, 200);
});
});
function details_in_popup(div_id, product_id){
$.ajax({
url: 'index.php?route=product/product/get_product_ajax',
type: 'post',
data: 'product_id=' + product_id,
dataType: 'json',
success: function(json){
if (json['success']) {
$('#' + div_id).html(json['success']);
}
}
});
return '<div id="'+ div_id +'">Loading...</div>';
}
Here is how my html structure looks like:
<div class="image">
<a data-unique="unique-3" data-product-id="39" rel="popover" href="link to product">
<img src="path to image" />
</a>
</div>
UPDATE:
Thanks everyone for your help and input. Here is how I fixed it:
function details_in_popup(div_id, product_id){
//I added this block
if ( $("#popover_content_for_prod_" + product_id).length ) {
return $("#popover_content_for_prod_" + product_id).html();
}
$.ajax({
url: 'index.php?route=product/product/get_product_ajax',
type: 'post',
data: 'product_id=' + product_id,
dataType: 'json',
success: function(json){
if (json['success']) {
$('#' + div_id).html(json['success']);
//Also added this line
$('body').append('<div style="display:none;" id="popover_content_for_prod_' + product_id + '">' + json['success'] + '</div>');
}
}
});
return '<div id="'+ div_id +'">Loading...</div>';
}
Use a hidden element to store the value of the
booleanand get it before the AJAX call then set it when done.HTML:
JS: