Erlaunis Erlaunis - 6 months ago 19
Ajax Question

Order of ajax requests is always different

I have a javascript code which have to request the database (ajax). But I discovered that the inserts were wrong but with the right sql request. So I added an alert on which ajax request to know when the code is executed.

Here is the code :

$.post("/kohana-v3.3.5/ajax/update_simulation", {
id_simulation: id_simulation,
nom_simulation: nom_simulation,
sol_simulation: sol_simulation,
station_simulation: station_simulation,
iteration_simulation: iteration_simulation,
scenario_simulation: scenario_simulation
}
, function (result) {
console.log(result);
alert('update');
});

$.post("/kohana-v3.3.5/ajax/delete_pousses", {id_simulation: id_simulation}, function (result) {
console.log(result);
alert('delete');
});

$(this).prev('div').find('table .formRows').each(function (i) {
alert('here');
if (cpt % 2 == 1) {
//interculture
var $tds = $(this).find('td option:selected'),
culture = $tds.eq(0).val(),
date = $tds.eq(1).text();
itk = null;
} else {
//culture
var $tds = $(this).find('td option:selected'),
culture = $tds.eq(0).val(),
itk = $tds.eq(1).val();
date = null;
}

$.post("/kohana-v3.3.5/ajax/insert_pousses", {
id_simulation: id_simulation,
culture: culture,
date: date,
itk: itk,
rang: cpt
}, function (result) {
console.log(result);
alert('insert');
}); //Fin du post

cpt++;


}); //Fin du each


Each time I run that code, the order of the alert is always different ! Sometimes "insert update delete", sometimes "update, delete insert" ...

And it's a problem because if the delete is the last one, the insert will be removed. So, is it a normal way ? How should I resolve it ?

Answer

AJAX requests are asynchronous, so you cannot guarantee an order if you trigger them as siblings like this.

In order to guarantee a fixed order, you need to make the subsequent call from the success block of its predecessor. Something like this:

$.post('/ajax/method1', { params: params }, 
  function(result) {
    $.post('/ajax/method2', { params: params }, 
      function(result) {
        $.post('/ajax/method3', { params: params }, 
          function(result) {
          });
      });
  });