Displaying a loading screen while a jQuery ajax request is in progress

Currently, I am attempting to display a loading div while waiting for an ajax call to finish. Despite experimenting with various methods, I have not been able to consistently achieve the desired outcome.

In my present code, everything functions properly only if I set a breakpoint on the function responsible for showing the div once the ajax request is complete.

Here's the Fiddle

var https = 'https://www.googleapis.com/calendar/v3/calendars/';

function HideCheckShowLoading(checkId) {
    $("#check_" + checkId).hide('slow', function() {
        $("#loading_" + checkId).show('slow');
    });
};

function HideLoadingShowCheck(checkId) {
    $("#loading_" + checkId).finish().hide('slow', function() {
        $("#check_" + checkId).finish().show('slow');
    });
};
$(document).ready(function() {
    $('#get').click(function() {
        HideCheckShowLoading(1);
        $.ajax({
            url: https,
            dataType: 'jsonp',
            type: "GET",
            success: function(response) {
                //do something
            },
            error: function() {
                //do something else                
            }
        }).done(function() {
            HideLoadingShowCheck(1)
        });

    });
    $('#get2').click(function() {
        HideLoadingShowCheck(1);
    });

});
#check_1
 {
    background-color:red;
}

#loading_1
 {
    background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="check_1">Check</div>
<div hidden id="loading_1">LOADING</div>
<button id="get">Get</button>
<button id="get2">Get2</button>

The desired functionality includes:

  1. Hiding the check div upon button click
  2. Displaying the loading div
  3. Performing the ajax call
  4. If successful, performing an action (reloading the contents of the check div)
  5. Hiding the loading div
  6. Showing the check div

Despite trying several methods I found, I keep encountering issues where only the loading div is displayed without further progress. Any help would be greatly appreciated!

Thank you

Answer №1

I think you might be overthinking things a bit here. A simpler approach could work just as well:

$('#get').click(function() {
    HideCheckShowLoading();
    $.ajax({
       url: https,
       dataType: 'jsonp',
       type: "GET",
       success: function (response) {
           //do something
       },
       error: function() {
           //do something else                
       },
       complete: HideLoadingShowCheck
   });
});

If you prefer not to trigger the HideLoadingShowCheck function after success or error, you can simply call it within those blocks instead of using complete.

Answer №2

Adding () to a function name causes it to be called immediately and return the result. The correct approach is to pass the function itself without using ().

If HideCheckShowLoading() does not involve an ajax call and jquery animations work differently, then there is no requirement for $.when. Additionally, since $.ajax returns the promise itself, the code can be updated as follows:

$(document).ready(function() {
    $('#get').click(function() {
        HideCheckShowLoading();
        $.ajax({
           url: https,
           dataType: 'jsonp',
           type: "GET",
           success: function (response) {
               //do something
           },
           error: function() {
               //do something else                
           }
        }) 
        //.done(HideLoadingShowCheck);
        .done(function() { HideLoadingShowCheck(otherparams); })
    });
});

To enhance the showcheck function, consider adding .finish() in case it is still animating from the showhide:

function HideLoadingShowCheck() {
    $("#loading").finish().hide('slow',function () {
        $("#check").finish().show('slow');
    });
};

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

Where can I find a CDN version of a block UI jQuery library?

I'm trying to find a more efficient way to use libraries like blockUI, preferably through a CDN rather than hosting it on my own site. Unfortunately, I keep encountering a 403 error when attempting to link directly to the blockUI file on github. Are t ...

Verify role declarations and display components if valid

I am currently developing an application using Angular on the front-end and ASP.NET on the back-end. Within this application, there are two roles: user and admin. I have implemented a navigation bar with several buttons that I need to hide based on the use ...

Retrieve the $ionicConfigProvider within a Controller

In my controller file named ProfileController.js, I am trying to change the text of the back button. After doing some research, I found this code snippet: $ionicConfigProvider.backButton.text('Go Back').icon('ion-chevron-left'); How can ...

Finding the parent div in the handleChange function using React

I am facing a challenge with multiple dynamic divs, as their number depends on the filter selected by the visitor. This makes it impossible to use getElementById in this scenario. My goal is to modify the parent div's CSS when an input is checked. B ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

Using the map function with a React onClick handler

After tirelessly scouring the internet for answers to my query, I've hit a dead end. My goal is to implement a basic react click handler on my button, but for some reason, it just won't cooperate. It's likely something incredibly straightfor ...

Using Flask and jQuery, learn how to toggle the visibility of a reply text box

After a break from using HTML/JavaScript, I find myself a bit puzzled about how to handle this. I'm working on creating a reddit-like clone with Flask. I've reached a point where I can add child comments to any comment and have them display nic ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Tips for dividing the WordPress header navigation horizontally using separate PHP files

I am trying to customize my WordPress menu navigation by splitting it into two sections: left and right. I have added the menu function in the "functions.php" file to create the menu from the backend, and the frontend modifications will be done in the "hea ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

Utilizing AJAX and JSF to implement automatic capitalization of letters

As a newcomer to AJAX, I am eager to implement a feature that automatically converts input text into capital letters after the keyup event. Can anyone guide me on how to achieve this using AJAX in conjunction with JSF? ...

Locate the <li> element within the list that was clicked on by the user using JQuery UI Selectable

I am trying to retrieve the <li> element that the user has clicked on in a jQueryUI selectable. The goal is to determine whether the clicked element is already selected or not and then take action based on that. The following code is what I have so f ...

What is the process for dynamically incorporating JavaScript files during compilation to serve as input for browserify?

Within our project's structure, there exists a directory housing multiple js files. The possibility of adding or removing these files later on is present. Currently, we have a file named main.js where each file is imported and a map is created (using ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...

The Bootstrap nav-justified feature fails to utilize the entire width available

Have you heard of the bootstrap-4 class called nav-pill? It's meant to make links have equal width and occupy all horizontal space. To achieve equal-width elements, simply use .nav-justified, as suggested. This will ensure that nav links take up al ...

Error in SO Embed Snippet Fiddle due to Bootstrap 4 JS Issue

Just wondering, any idea why the bootstrap 4 js is throwing this error: https://i.sstatic.net/J4Iq4.png when trying to embed the snippet? (No errors in the external Fiddle) Added tether.js but no luck (kept it commented). Switched to jQuery 2.2.1 on th ...

I'm experiencing an issue when trying to align TextPath to the center in an SVG file - a certain character

When using the startOffset or text-anchor attributes, I noticed that some characters are missing. How can I fix this issue? Thank you. It appears that in this scenario, the characters `1234` are missing. <svg xmlns="http://www.w3.org/2000/svg" versi ...

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...

Hiding the title property while displaying a JQuery tooltip

I have implemented a simple JQuery solution for creating hovering tooltips using text from elements' title attribute. While it is functioning adequately, I am looking to prevent the default browser behavior associated with the title attribute from occ ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...