John John - 5 months ago 28
Javascript Question

Loading AJAX calls one after the other

Good day everyone,

I have the following 3 AJAX function, and the problem is that it loads sessionAllCoursePage3 first then sessionAllCoursePage2 then sessionAllCoursePage1, I wanted to be inverse. I want to ensure that page1 is loaded first, then page 2, page 3, etc.

// Retrieve last 9 session
$.ajax({
type: "POST",
data: {run: true, providerName: $('#providerName').val()},
url: '/app/functions/sessionAllCoursePage1.php',
cache:false,
success: function (response) {//response is value returned from php (
$('#contentPage1').html(response);
return false;
}
});

// Retrieve the next 9 session

$.ajax({
type: "POST",
data: {run: true, providerName: $('#providerName').val()},
url: '/app/functions/sessionAllCoursePage2.php',
cache:false,
success: function (response) {//response is value returned from php (
$('#contentPage2').html(response);
return false;
}
});

// Retrieve the next 9 session

$.ajax({
type: "POST",
data: {run: true, providerName: $('#providerName').val()},
url: '/app/functions/sessionAllCoursePage3.php',
cache:false,
success: function (response) {//response is value returned from php (
$('#contentPage3').html(response);
return false;
}
});

Answer

You can use Array.prototype.shift(), String.prototype.match() with Regexp /\d/ to match digit character in url, .then()

   function request(url) {
      return $.ajax({
        type: "POST",
        data: {run: true, providerName: $('#providerName').val()},
        url: url,
        cache:false,
        success: function (response) {
            $('#contentPage' + url.match(/\d/)[0]).html(response);
      }
     });
    }

var urls = ['/app/functions/sessionAllCoursePage1.php'
           , '/app/functions/sessionAllCoursePage2.php'
           , '/app/functions/sessionAllCoursePage3.php'];

request(urls.shift())
.then(() => request(urls.shift()))
.then(() => request(urls.shift()))
Comments