0

I am creating a drop down list in JavaScript, I am loading the data via Ajax and JSON, at the moment my code loops through a set of departments and runs into the ajax call in each iteration.

My problem is that my data seems to be appending in a random order, its likely that its loading in the order of whichever loads quickest.

I want to be able to loop through my Ajax call and append the data in the order that I declare (for each department). is this something that can be done?

Here is my code:

//-- Ajax --
var departments = ['Accounts', 'Commercial', 'Installation', 'Production', 'Sales'];
var i;

for (i = 0; i < departments.length; i++) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/EmployeesDropDown",
        data: '{X: "' + departments[i] + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "text json",
        async: true,
        success: createdropdown,
        failure: function () {
            alert("FAIL!");
        }
    });
}


//-- Creates dropdown --
function createdropdown(data) {
...appends all the data to my drop down list...
  }

Any help or advice is appreciated, thank you in advance.

EDIT: This question is different from the related ones because I need to be able to loop through the string array, rather than just iterating based on numbers.

daniel aagentah
  • 1,672
  • 5
  • 29
  • 56

1 Answers1

0

If you want to load the departments in the order they appear in the departments array you could load them one by one, waiting for each ajax request to finish until you start the next request.

Here is an example:

var departments = ['Accounts', 'Commercial', 'Installation', 'Production', 'Sales'];
var i = 0;

function reqDep(department) {

  /*
  Since i can't use ajax here let's use a promise.
  */

  var p = new Promise(function(res, rej) {
    setTimeout(function() {
      res(department)
    }, 1000)
  })
  return p;

  // This is what you would actually do.

  /*
  var data =  '{X: "' + department + '"}'
  return $.ajax({
    type: "POST",
    url: "Default.aspx/EmployeesDropDown",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "text json",
  });
  */  
}

function initDepartments(index) {
  reqDep(departments[index])
  // Here you would use `.done(function(data...`
  // I am using `.then(function(data...`
  // because of the promise.
  .then(function(data) {
    console.log(data)
    if(i < departments.length) {
      initDepartments(i)
    }
  })
  i++;
};

initDepartments(i)
DavidDomain
  • 14,976
  • 4
  • 42
  • 50