Stop a second ajax request while the first one is in progress

Despite the abundance of questions on Stack Overflow addressing this issue, I still can't find a solution.

Here is the jQuery code snippet:

function _get_activities_ajax() {
    $(".activity-accordian h3").click(function() {
        var catrgory      = $(this).attr("data-subject");
        var catId      = $(this).attr("id");
        if($("#"+catId+"-wrap ul").children().length==0) { 
        $("#"+catId+"-wrap").append("<div class='preloader'></div>");
            $.ajax({
                url: _getActivityAjax,
                data: {catrgory: catrgory},
                type: 'POST',
                success: function(result) {
                    $(".preloader").remove();
                    $("#"+catId+"-wrap").append(result);
                },
                error: function(e) {

                }  
            });
        }
        $(".activity-accordian h3").removeClass("active-header").removeClass("header-1");
        $(this).addClass("active-header");

        $(".categ-content ul").css("display","none");  
        $("#"+catId+"-wrap ul").css("display","block"); 
    });  
}

This code snippet is designed to fetch datasets for an accordion UI.

I am looking for a way to prevent making a second call until the first one is completed. Any assistance would be greatly appreciated.

Thank you!

Answer №1

Create a variable to keep track of the status of your Ajax request.

JavaScript

function _get_activities_ajax() {

    //Variable to store ajax call status
    var ajaxStatus = true;

    $(".activity-accordian h3").click(function() {
        var category  = $(this).attr("data-subject");
        var catId   = $(this).attr("id");

        if($("#"+catId+"-wrap ul").children().length==0  && ajaxStatus) { //check if true

            //Set status to false for new ajax call
            ajaxStatus = false;

            $.ajax({
                url: _getActivityAjax,
                data: {category: category},
                type: 'POST',
                success: function(result) {

                    //Set status back to true after successful call
                    ajaxStatus = true;
                },
                error: function(e) {


                    //In case of error, set status back to true
                    ajaxStatus = true;

                }  
            });
        }

        ...
    });  
}

Answer №2

In the past, similar issues were resolved by avoiding the use of the async property in ajax calls, as it would freeze the GUI temporarily. Instead, developers found a better solution by utilizing callbacks.

To implement this in your code, you can make another ajax call within the success callback of the first one.

For example:

$.ajax({
    url: _getActivityAjax,
    data: {catrgory: catrgory},
    type: 'POST',
    success: function(result) {
        $(".preloader").remove();
        $("#"+catId+"-wrap").append(result);
        //Add your second ajax call here    
    },
    error: function(e) {

    }  
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...

Is there a way for me to access the "ViewBag" value from the Controller in a JavaScript file following an Ajax response?

How can I access the ViewBag value that has been initialized in one Action method before making an Ajax call to another Action Method in my JavaScript file? Any assistance would be greatly appreciated. ...

Dynamic content loading using AJAX to selectively update a designated section

I am having trouble displaying the error message in my form. Currently, it is causing my form page to load four times. Can someone help me identify what I did wrong? I only want to display that span: controllers: <?php /* * File Name: user.php */ ...

Saving a session variable to the database using ajax technology

If you're like me and struggling to figure out how to add a session variable (username) to a database using ajax, I've been there. My limited knowledge of jQuery and JavaScript made it quite the challenge. The dynamic table I'm working with ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Remove Chosen Pictures (Checkbox/PHP/MySQL)

I am currently displaying images from a Database using the following HTML code: <li> <input type="checkbox" id="1" /> <a rel="gallery_group" href="images/big/1.jpg" title="Image 1"> <img src="images/small/1.jpg" alt="" ...

What is the best way to send an Ajax Json Response to a php script?

My current setup involves an Ajax call using the xmlHttpRequest to retrieve data from a server. I aim to format this response into a specific string and share it on a different server. To achieve my goal, I am leveraging a php script for processing the fo ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Using the jQuery AJAX function to modify the URL query string

I currently find myself on a webpage Is there a way to add a URL query string without reloading the page? For example, when I click a button, can the URL change to using jQuery ajax functions? ...

The jQuery validation error message states that the object 'this.0.form' is either null or does not exist

My code is generating an error in ie7 that says 'this.0.form' is null or not an object. The issue occurs when a button triggers the form to submit upon being clicked. In other browsers, the form is validated by the validation plugin without any p ...

The margin property in jQuery does not seem to be functioning properly when trying to send

Within the view page, there is jQuery code that sets a margin on a div. Below is the code: <script type='text/javascript'> $('#someID').css('margin-left', '10px'); </script> This code functions proper ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Parsing nested JSON files to present data on a webpage

I have a JSON file containing Reddit post titles and their respective scores: { "'JavaFX Simple Inventory Management App - Open source'": 39, "'Creating Formula Dependency Maps from Excel Spreadsheets'": 5, "'CVE-2017-5645 ...

Error Encountered: Django - AJAX Request Not Found

I'm currently working on building an ajax function that, when triggered, should display information in a newly created modal. I seem to be encountering an error that says "not found" every time I attempt to access the specified URL. Below is a screens ...

Strange Behavior of Zoom DIV Effect during Rapid Hovering

Here is the code I am working with: http://jsfiddle.net/8fvJN/15/ Whenever I try to quickly hover from one box to the next, a strange effect occurs where they start behaving erratically. If you hover between boxes rapidly, you will observe this behavior. ...

Slideshow plugin glitch on Safari and Opera caused by jQuery implementation

My current project involves utilizing a fantastic plugin called Sequence.js for creating animations and transitions with CSS3 based on jQuery. I have set up a simple responsive fadeIn-fadeOut slideshow using this plugin. While everything works smoothly an ...

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...