Search code examples
javascripthtmlcssbootstrap-5bootstrap5-modal

bootstrap 5 loading spinner in modal during xmlhttprequest


i'm making a xmlhttprequest in javascript and i'm using a bootstrap spinner in a modal to show the user its loading, it toggles the modal fine but can't hide it once loading is finished?

I'm trying to do this in vanilla javascript, since i'm more familiar with it, but i can use jquery if needed :]

I'm using google.com as an example for privacy reasons

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/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/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>

Any help would be greatly appreciated. Thanks!


Solution

  • try declaring modal variable once and set variable once++ before modal show

      var once = 0;
        var modal = new bootstrap.Modal(document.getElementById("loading"), {});
        var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    modal.hide();
                }
                else {
                    if (once == 0) {
        
                    once++;
                    modal.show();
                    } else {
                      modal.hide();
                    }
                }
            };
            xhttp.open("GET", "google.com", true);
            xhttp.send();