Creating a loading spinner in a Bootstrap 5 modal while making an XMLHttpRequest

While working on a xmlhttprequest in JavaScript, I incorporated a bootstrap spinner within a modal to indicate loading. The modal toggles correctly, but I am struggling to hide it once the loading is complete.

I prefer using vanilla JavaScript for this task due to my familiarity with it, although I also have no issue switching to jQuery if necessary :]

For privacy reasons, I'm utilizing google.com as an example.

var once = 0;
var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var modal = new bootstrap.Modal(document.getElementById("loading"), {});
            modal.hide();
        }
        else {
            if (once == 0) {
            var modal = new bootstrap.Modal(document.getElementById("loading"), {});
            modal.show();
            once++;
            }
        }
    };
    xhttp.open("GET", "google.com", true);
    xhttp.send();
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap 5 Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12707d7d66616660736252273c203c22">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9cbc6c6dddfdddcdadacbc88dbdbdeabeeebabdbeedfdbffbbba898bdc879cecfc">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="modal" style="background: none !important;" id="loading" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="background: none !important;">
    <div class="modal-content" style="background: none !important; border: none;">
      <div class="modal-body" style="background: none !important; text-align: center;">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>

If anyone could provide assistance, it would be highly appreciated. Thank you!

Answer №1

Ensure to initialize the modal variable once and set a variable to keep track of it before showing the modal.

var initialized = 0;
var modalWindow = new bootstrap.Modal(document.getElementById("loading"), {});
var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            modalWindow.hide();
        }
        else {
            if (initialized == 0) {

                initialized++;
                modalWindow.show();
            } else {
                modalWindow.hide();
            }
        }
    };
    request.open("GET", "example.com", true);
    request.send();

Answer №2

fetch in combination with async functions are well supported, making the use of XMLHttpRequest unnecessary:

async fetchData() {
  const modal = new bootstrap.Modal(document.getElementById("loading"), {});
  modal.show();

  try {
    const response = await fetch('your-url', /* options */);
    if (response.ok) { // Successful response
      const data = await response.text(); // or response.json() for JSON data
      // Handle the data accordingly
    } else {
      // Error handling logic
    }
  } catch(error) {
    // More error handling here
  } finally {
    // hide the spinner after request completion
    modal.hide();
  }
}

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

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

What is the best way to generate a box when a button is pushed?

How can I make a button create a box with text inside it when clicked? <div class="trades"> </div> <button onclick="create()">add</button> Here is the JavaScript function to create the box: function create() { var box = docu ...

Whenever I utilize paesrInt in the POST request, an error occurs. I have included the code below for reference

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.get("/", function (req, res) { res.sendFile( ...

Trouble Loading TypeScript Class in Cast Situation

I've encountered an issue with my TypeScript model while using it in a cast. The model does not load properly when the application is running, preventing me from accessing any functions within it. Model export class DataIDElement extends HTMLElement ...

``There seems to be a problem regarding the alignment of elements in

Having some trouble with centering the grid on my simple website. As a beginner in Bootstrap, I'm seeking guidance. Will be grateful for any help you can offer! Please bear with me as I learn. <html> <head> <meta charset="utf8"/& ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Struggling to keep up with responsive behavior on a page featuring vertically and horizontally centered content that spans the full height

I'm working on a full-height website and the first section needs to have both vertical and horizontal centered content. The issue I'm facing is that there's an image included, which doesn't scale responsively when the screen size change ...

Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically. Here is the HTML snippet: <div class="alert alert-success alert-dismissible fade show" role="alert" id="accepted-meal-al ...

AngularJS Custom Navigation based on User Roles

I am currently developing a small web application using angular. My goal is to implement role-based navigation in the app. However, I am facing an issue where the isAdmin function does not seem to be getting called on page load, resulting in only the foo a ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

The error message "Angular formGroup requires a FormGroup instance. Kindly provide one."

I used angular reactiveforms to create a form. The default data is successfully printed on the form, however, I am facing an error in the console that says "formGroup expects a FormGroup instance. Please pass one in." Can someone guide me on how to resolve ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

What is the best way to use command line arguments within a Node.js script?

As a newcomer to the world of programming, I find myself struggling to make progress despite putting in significant effort. Although it may seem like a trivial question, my lack of progress is becoming frustrating. Currently, I am working on a node.js scr ...

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...

Is there a way to use Jquery to determine if a parent div contains a scroll

I'm trying to find a jQuery example that checks if any parent div has a scroll bar, but I can't seem to locate a helpful one. Here is the code snippet I am working with: <div> <div class="heading"> <div class="visit ...

Difficulty occurred when trying to import Polymer components

Currently, I am in the process of learning how to utilize Polymer. I meticulously followed the instructions provided exactly as specified here. However, upon reaching step 3 and adding the import for paper-checkbox, an error presented itself: Error: A c ...

Embedding an Iframe in the Main URL

I have a specific request where I've inserted an anchor tag within an IFRAME. Currently, when the anchor link is clicked, the page redirects within the IFRAME. However, I need the functionality to redirect to the main URL instead of staying within the ...

Every time I click, the click event is getting attached repeatedly through the on method

Here is the HTML code that I am working with: <div class="connect"> <ul> <li><a href="#">Assign a Task</a></li> <li><a attr="viewCard" href="#">View Ca ...

Send the DOM element to a processing function within AngularJS

In this code snippet, there is an attempt to pass a table cell (as a DOM object) to a function. However, it seems that the reference of 'this' does not point to the DOM object for the table cell, but rather to '$scope'. Any suggestions ...

There seems to be an issue with the visibility of the b-button within the b-table component in

I'm new to Vue Js and I'm having trouble with my b-button not displaying in my table. I can't figure out why. Below is my HTML code: <div id="listlocales"> <div class="overflow-auto"> ...