Jeremy Ruffell
Jeremy Ruffell

Reputation: 45

Running a function while waiting for ajax request to complete

I am trying to solve a problem I have and I am a bit stuck with how to do this.

I am currently posting to my PHP page via AJAX, and while I am waiting for the request to respond I am wanting to run a function that simply displays loading.. and adds an additional '.' every 100ms. My problem is How can I call a function and then 'stop' that function when my ajax request has completed?

I have tried some promise based code but I want to know what is the best approach to do what I am trying to do?

$.ajax({
  type: "POST",
  url: "controllers/register.php",
  data: $("form").serialize(),
  beforeSend:() => {
    // Start LoadingBar() Here.
  },
  success:() => {
    // Stop LoadingBar() Here.
  }
})

function LoadingBar() {
  let elem = document.getElementById('para');
  elem.innerHTML += "Loading ."

  setInterval(() => {
    elem.innerHTML += " ."
  }, 100);
}

Any help or any direction on where I can find the information to figure this out would be much appreciated.

Upvotes: 2

Views: 95

Answers (5)

EternalHour
EternalHour

Reputation: 8621

You are close. Now simply use clearInterval in the success callback to stop the function once the request is complete. Also, avoid mixing vanilla JS with JQuery.

Here's a working JSFiddle based on your code so you can see it in action.

function LoadingBar() {
  $('#para').html('Loading .');

  loading = setInterval(() => {
    $('#para').append(" .");
  }, 100);
}

$(function() {
  $.ajax({
    type: "POST",
    url: "controllers/register.php",
    data: $("form").serialize(),
    beforeSend: () => {
      LoadingBar();
    },
    success: (data) => {
      clearInterval(loading);
      $('#para').html(data);
    }
  });
});

Upvotes: 1

Soc
Soc

Reputation: 7780

Use clearInterval.

Example:

let intervalId;

$.ajax({
  type: "POST",
  url: "controllers/register.php",
  data: $("form").serialize(),
  beforeSend:() => {
    startLoading();
  },
  success:() => {
    stopLoading();
  }
})

function startLoading() {
  let elem = document.getElementById('para');
  elem.innerHTML += "Loading ."

  intervalId = setInterval(() => {
    elem.innerHTML += " ."
  }, 100);
}

function stopLoading() {
  clearInterval(intervalId);
}

Upvotes: 0

Chris
Chris

Reputation: 7278

How can I call a function and then 'stop' that function when my ajax request has completed?

Use setInterval to add the dots to your progress bar, then clear the returned handle with clearTimeout when the request completes.

Here's a simple example just using a callback (assumes jQuery). The cool kids use either promises or async/await nowadays, but it all the same under the hood.

function load() {
  // Start the animation.
  $('#results').hide();
  $('#progress-bar').show();

  const timeoutHandle = setInterval(incrementProgress, 100);

  fakeRequest(function successCallback() {
    // When the request is done...

    // 1. Clean up the animation timer.
    clearTimeout(timeoutHandle);

    // 2. Display results and hide the animation.
    $('#progress-bar').hide();
    $('#results').show();
  });
}

function incrementProgress() {
  $('#progress-bar').get(0).innerHTML += '.';
}

function fakeRequest(callback) {
  // This doesn't actually load data.
  // Launch your ajax request instead.
  setTimeout(callback, 1000);
}

fiddle

Upvotes: 1

Amit Rai
Amit Rai

Reputation: 397

 let elem = document.getElementById('para');
  elem.innerHTML += "Loading ."

    $.ajax({
      type: "POST",
      url: "controllers/register.php",
      data: $("form").serialize(),

      success:() => {
 let elem = document.getElementById('para');  
 elem.innerHTML += " ."

      },
error:() => {
          let elem = document.getElementById('para');  
         elem.innerHTML += " ."
          }
    })

before calling ajax call all loading to inner HTML and on success or error remove it

Upvotes: 0

Sajad Haibat
Sajad Haibat

Reputation: 717

Use this approach: it will dispaly a gif spinner or loader on every ajax call on that page, so just add this function on your js file and give the path to that image.

  // Add Loader on every ajax calls
        $("body").once('body').prepend("<div id='spinner-amt'><img src='/assets/images/spinner.gif'></div>");
        $(document).ajaxSend(function(){
          $('#spinner-amt').show();
        });
        $(document).ajaxComplete(function(){
          $('#spinner-amt').hide();
        });

and if you want to design the loader, just add the following css to youe css file. following css will show the spinner the middle of the page.

#spinner-amt {
  width: 100%;
  position: fixed;
  z-index: 99999;
  height: 100%;
  text-align: center;
  padding-top: 45vh;
}

Upvotes: 1

Related Questions