Aniket Singh Aniket Singh - 1 year ago 84
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

$("#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') {
$("#tooltip").html(item.series.label + " of " + x + " = " + y)
top: item.pageY + 5,
left: item.pageX + 5
} else {

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download