Home / Prevent an AJAX request firing twice with jQuery

Prevent an AJAX request firing twice with jQuery

I was asked on my post about showing a loading image when loading AJAX content with jQuery how to disable the button that loads the content while it’s loading, and then re-enable it again once the content is fully loaded. This post shows how to do this, and it will work whether it’s a link, button or some other action which calls the AJAX loading function.

The Javascript/jQuery code

If it’s a button you could simply disable it at the start of the request and then enable it again in the callback function when the AJAX request has finished loading. But this won’t work if it’s a link or some other action making the request.

So let’s use a global variable instead which stores the loading state and conditionally make the AJAX request based on the current value of the loading variable.

Here’s some HTML showing an anchor tag and a content placeholder. The anchor links directly to a content page, but the Javascript code below will re-bind the action of the link to the AJAX request function:

<a id="ajaxRequestor" href="/path/to/content.html" target="_blank">Load</a>
<div id="ajaxContentPlaceholder"></div>

And now here’s the Javascript

var ajaxLoading = false;
$(document).ready(function() {
    $('#ajaxRequestor').click(function(e) {
        e.preventDefault();
        if(!ajaxLoading) {
            ajaxLoading = true;
            $('#ajaxContentPlaceholder').load('/path/to/content.html', 
                function() { 
                    ajaxLoading = false;
                }
            );
        }
    });
});

Line 1 sets up the global variable, defaulting it to false.

Line 3 assigns a click handler to the #ajaxRequestor link and prevents the default action from occuring on line 4; this means that clicking the link will now only do the code in the function and not follow the link. See my previous post disable a link from going to the href URL with jQuery for more details about this.

The block of code that then makes the request is only run if the global variable "ajaxLoading" is currently false. The first thing it does is to set ajaxLoading to true (line 6) so that if the link is clicked again then the request is not done a second time.

Finally, the request itself is made on line 7, by loading the content from /path/to/content.html into the #ajaxContentPlaceholder div.

The callback function on lines 8 to 10 is passed as the second parameter and is called once the AJAX request has completed. It sets ajaxLoading back to false so if the link is clicked again the content will be loaded again.

If you only ever wanted the content to be loaded once you could leave the callback function out, and rename the variable to something more appropriate like "ajaxLoaded". You might also want to have an array or other variable naming scheme depending if there are more than one AJAX requests on a single page.