3

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 ?

Erlaunis
  • 1,433
  • 6
  • 32
  • 50
  • The `a` in `ajax` stands for `asynchronous`. Which means that the execution of the post request will not run in order. Whichever one happens to to be the fastest will return first. – Jack May 19 '16 at 14:26

4 Answers4

4

javascript can be executed asynchronously - and that's the reason why your ajax requests are not always executed in the same order. You can set them asnyc false (like here jQuery: Performing synchronous AJAX requests) or make something like promises (https://api.jquery.com/promise/) to wait for the ajax call to be finished.

greetings

Community
  • 1
  • 1
messerbill
  • 5,499
  • 1
  • 27
  • 38
3

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) {
          });
      });
  });
GalacticCowboy
  • 11,663
  • 2
  • 41
  • 66
  • I tried, but the third `post` is actually inside a function which loop through a table. I edited my post for you to see. – Erlaunis May 19 '16 at 14:30
  • @Erlaunis That should work the same. Or you could split them into entirely different functions and call each function in turn. – GalacticCowboy May 19 '16 at 14:38
  • Ok, I had a problem with the `$(this)` inside the success function of ajax. But I fixed it ! Thanks :) – Erlaunis May 19 '16 at 14:44
3

You can use .promise to "observe when all actions of a certain type bound to the collection, queued or not, have finished."

https://api.jquery.com/promise/

Example Function

function testFunction() {
    var deferred = $.Deferred();

    $.ajax({
        type: "POST",
        url: "",
        success: function (data) {

           deferred.resolve(data);
        }
    });
    return deferred.promise();
}

Calling Function

function CallingFunction() 
{
     var promise = testFunction();

     promise.then(function (data) {

         //do bits / call next funtion
     }
}

Update

This may also help you out:

"Register a handler to be called when all Ajax requests have completed."

https://api.jquery.com/ajaxStop/

$(document).ajaxStop(function () {

});

Final note:

As of jQuery 1.8, the use of async: false is deprecated, use with $.Deferred.

David
  • 641
  • 1
  • 8
  • 23
  • I used the solution of GalacticCowBoy, but every functions you talk about are really interesting, I probably use them later. Thanks ! – Erlaunis May 19 '16 at 14:46
1

you need to call post ajax method after by the success of previous one.

like:

 $.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');
    dleteajax();
            });

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