The values in DataTable are switched

Viewed 52

I want to render a table after executing ajax. Here, I am using jQuery

var tableOfSomething = $('#some_id').DataTable({
            "paging": true,
            "lengthChange": true,
            "searching": true,
            "ordering": true,
            "info": true,
            "autoWidth": true,
            "responsive": true,
        });

$.ajax({
   method: "POST",
   url: "someurl.com/getAll"
   data: {}
})
   .done(function(msg){
      var res = JSON.parse(msg);
      for(var i = 0; i < res.length; i++){
         $.ajax({
            method: "POST",
            url: "someurl.com/getDataById"
            data: {res[i]['id']}
         })
            .done(function(msg){
               var data = JSON.parse(msg);
               var body = data['body'];

               var result = res;

               tableOfSomething.row.add([
                  body['name'],
                  result[i]['a'],
                  result[i]['b'],
                  result[i]['c'],
                  result[i]['d']
               ]).draw(false);
            })
      }
   });

The problem is, the first column often switched each other. Says that body['name'] or first column of each row is Maria, Jonathan, Jon Doe. That names, often change, but the other column doesn't.

I have tried to use success as key of and move the function in done() as value of success, but the result is same. I try many thing i can do, but its same. Is there some problem with my code? Any body can help me?

1 Answers

You are using asynchronous variables in a synchronous loop. i have increased to last possible value long before the first ajax call is finished. Not tested, but believe this could be solved by a simple closure (i) :

    for(var i = 0; i < res.length; i++) {
      (function(i){
         $.ajax({
           method: "POST",
           url: "someurl.com/getDataById"
           data: {res[i]['id']}
         })
         .done(function(msg){
            var data = JSON.parse(msg);
            var body = data['body'];
            var result = res;
            tableOfSomething.row.add([
               body['name'],
               result[i]['a'],
               result[i]['b'],
               result[i]['c'],
               result[i]['d']
            ]).draw(false);
         })
      })(i);
   }
Related