Aniket Singh Aniket Singh - 6 months ago 15
Ajax Question

How to avoid or stop multiple ajax request

I am using the flotchart plugin, and I was trying to know when and where the user hovers on the chart and get more information from database regarding that chart value.

For example, if the user hovers on a date like "24 May" then an ajax call will be made and all the data for "24 May" will be appended to a div.

Here is my code

$("<div id='tooltip'></div>").css({
position: "absolute",
display: "none",
border: "1px solid #fdd",
padding: "2px",
"background-color": "#fee",
opacity: 0.80
}).appendTo("body");

$("#visitor-chart").on("plothover", function(event, pos, item) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
if (typeof x !== 'undefined') {
$.get("/ajax/graph?param="+item.datapoint[0]).done(function(result){
$("#graf").html(result);
})
}
$("#tooltip").html(item.series.label + " of " + x + " = " + y)
.css({
top: item.pageY + 5,
left: item.pageX + 5
})
.fadeIn(200);
} else {
$("#tooltip").hide();
}
});


Now the problem is whenever I hover on any date, it sends multiple ajax requests like 10-15 requests immediately. How can I avoid extra ajax requests?

Answer

You can do this by adding a flag to the top of the function which checks to see if the ajax call has been fired. Here is some sudo code, obviously you will need to make this work with your example.

var isAjaxing = false
$().on("click", function(){
    if(isAjaxing) return;
    isAjaxing = true;

    $.ajax(url, function(){
       isAjaxing = false;
    })
})

This will lock out the function until the ajax call is complete.