Is there a way to repeatedly apply addClass / removeClass functions multiple times?

I am having an issue where I want to display a loading icon using CSS on my page when a user sends data via ajax, and then remove this loading icon once the ajax call is complete. The strange thing is that the page successfully shows the icon the first time, but it does not show again without a page refresh. However, the ajax call is being completed successfully for multiple calls. Here is the code snippet:

Relevant Html:

<head>
<link rel="stylesheet" href="~/Content/Loading.css" type="text/css&quot; id="loading_gif"/>
</head>
...
...
<button type="button" class="btn btn-success" id="button">Import</button>
...
...
<div class="modal"><!-- Placed at bottom of page --></div>

Ajax:

$(document).ready(function () {
    $('#button').click(function () {                        
        $.ajax({
            type: "POST",
            url: '@Url.Action("Submit")',
            data: { 
              //submit data via jQuery 
            },
            dataType: 'json',
            beforeSend: function() {
                $body.addClass("loading");                        
            },
            success: function (data) {                        
                //render a partialView                    
            },
            complete: function () {
                $body.removeClass("loading");
            }
        });                
    });
}(jQuery));

CSS:

.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba( 128, 128, 128, .5 ) url('../img/ajax-loader-bar.gif') 50% 50% no-repeat;
}

/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.loading {
  overflow: hidden;
}

/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
  display: block;
}

Answer №1

Enhancing ajax calls globally

To gain insights, refer to this valuable answer:

You can also view a demo in this fiddle demonstrating the addition and removal of the loading class: http://jsfiddle.net/0fpdud5h/

jQuery.ajaxSetup({
  beforeSend: function() {
     body.addClass('loading');
  },
  complete: function(){
     body.removeClass('loading');
  },
  success: function() {}
});

This functionality may be triggered multiple times on the provided fiddle. May this serve as a helpful starting point for you.

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

Sending a form to an iframe with Jquery

I am attempting to display a SSRS report with parameters in an IFrame using Jquery. My current approach involves using the Form target attribute to load it into the IFrame, but it ends up opening in a new window instead. Here is the HTML Code: <iframe ...

Transferring data through Ajax and Json to upload files

I'm looking to utilize ajax and json to upload a file. My PHP file contains a form with multipart functionality. I need to pass a file from my js file using ajax and json to the upload file. The part of the code causing me trouble is related to the al ...

Transmit information from an HTML form to an Express API

I'm currently in the process of creating a login page for users and I need to figure out how to send the login information to my express server. Unfortunately, I am struggling with calling the api for my server and sending the data across. When I atte ...

Switching Text Box Content When Hovering Over a Static Element: A Fail-proof Method

Even though I followed the solution from another source, the Description I set still refuses to show up in the text box. I have already attempted this: How To Change Text Box Content On Hover I meticulously checked every class name and every bracket in th ...

I'm having trouble extracting data into my HTML file using the append function in Jquery. What could be causing this issue?

Hey there, I'm having some trouble extracting data from a URL to my HTML file using jQuery. Can anyone help out? I'm still new to this. Here's the code <html> <head> <title> My Program </title> <script src="ht ...

How can I globally assign a JavaScript variable based on an AJAX response?

Here is the ajax code I have: <script> $('a[data-id]').click(function () { var id = $(this).attr('data-id'); var domain = $(this).attr('data-domain'); $.ajax({ url: 'getdata& ...

Transfer information to Google Sheet using AJAX

I've been attempting to transfer data to a Google Sheet using an HTML form. I came across this tutorial that provided guidance on how to achieve this: https://medium.com/@dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952c ...

What is the best way to update the content of a div on an HTML page by incorporating the content of a div from a different page using JavaScript?

I have a requirement where I need to implement a link in a Table of Contents that, upon clicking, should replace the existing content of one div on a page with the content of another div on a different page. My goal is to accomplish this using only JavaScr ...

When implementing a helper function in ejs with .then, the result returned is an [ object promise ]

I am facing an issue in my ejs file where I am invoking a helper function from another file that should return a result from MySQL. However, the problem lies in the fact that the returned value is showing as [ object promise ] even though I am using .then( ...

Modular Angular Component

I'm currently developing a language learning application using Angular 15. With numerous pages and components featuring diverse content, I am exploring the option of allowing users to customize the font type, size, and other display settings for each ...

Is it possible to simulate a 'click' on the pageAction button within a Chrome extension using programming?

I created a Chrome extension that includes a pageAction button. When the user clicks on this button, a popup.html window appears for them to take action. Is there a method to style a link on the page in a way that when clicked, it automatically triggers a ...

What methods can I use to prevent the page from reloading in a HTML "menu dropdown" using JQUERY?

<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" type="button" aria-expanded="true"> <span class="visible-sm-inline visible-md-inline visible-lg-inline">Sort by</span> <span class="visible-xs-inlin ...

Retrieve the HTML content of a webpage after selecting a value from the <option> tag

After selecting the value of options, I require the HTML of the page. url="http://ceogoa.nic.in/appln/UIL/ElectoralRoll.aspx" url=html(url) text=url%>%html_nodes(xpath='//*@id="ctl00_Main_drpAC"]/option')%>%html_text() values=url%>%htm ...

The variable $ has not been defined in Jquery framework

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="deployJava.js"></script> <script type="text/javascr ...

The controller action cannot be accessed through an ajax post request

Today is my first time using .net Core, and I am trying to make an ajax call to an action method: This is my Ajax call (from a regular HTML page) $("#contactMap").click(function (e) { e.preventDefault(); var url = "/MapObjects/mapC ...

Generating an HTML table by retrieving information from a database with the help of PHP

I have been working on a project that involves extracting data from a SQL database using PHP and then creating an HTML table based on that data. This table is designed to list the items I am selling, along with their costs, weights, and other relevant deta ...

The integration of Ajax and Datatables to implement a CRUD table functionality is not functioning properly

I'm currently facing an issue while trying to display data in my CRUD table using Ajax + Datatables. I am able to retrieve the JSON response with the necessary data from my database, but for some reason, it's not getting displayed on the table. ...

What is the solution to adding values from a counter?

I am trying to create a JavaScript counter: function animateSun() { var $elie = $("#sun"); $({ degree: 0 }).animate({ degree: 360 }, { duration: 190999, easing: 'linear', step: function(val) { now = Math.round ...

Having trouble getting the HTML5 Video to play using the AngularJS ng-src tag?

There seems to be an issue with AngularJS ng-src not working properly with the HTML5 Video element in this specific fiddle: http://jsfiddle.net/FsHah/5/ Upon inspecting the video element, it appears that the src tag is correctly filled with the appropriat ...

The function of the Nuxt.js server-side plugin is not functioning as intended

I recently developed a server-side plugin and encountered the following error: context.app.handleServerError is not a function // hanlde-server-error.js export default ({ app }, inject) => { app.handleServerError = (method, error, data) => { ...