Synchronize Ajax

2

I have an application in which I download all the data when the user logs. I need some data to be downloaded in full to go to the beginning of the application, because if they are not recovered, there may be errors.

Now I have Ajax in this way where under the data:

    $.ajax({
      url: "cientes.php",
      dataType: "json"
    }).done(function() {
      .....
      .....
    });

$.ajax({
      url: "facturas.php",
      dataType: "json"
    }).done(function() {
      .....
      .....
    });

How can I make sure that until the two are downloaded, the% start_co% of the application is executed?

    
asked by Juan Cubillos 27.05.2017 в 06:44
source

2 answers

1

You can apply JQuery Deferreds, it allows you to chain several asynchronous callbacks, in a synchronous execution line. In other words, in the case of your question, make sure that the callback of the start of your application is called, only when the two ajax have been made.

function successFunc() {
    console.log( "success!" );
    inicio();
}

function failureFunc() {
    console.log( "failure!" );
}

$.when(
    $.ajax( "clientes.php" ),
    $.ajax( "facturas.php" )
).then( successFunc, failureFunc );
    
answered by 27.05.2017 / 06:54
source
0

Try adding the option async with value false (default is true) in every Ajax request.

$.ajax({
    url: "cientes.php",
    dataType: "json",
    async:false
}).done(function() {
/*      .....
      ..... */
});


$.ajax({
    url: "facturas.php",
    dataType: "json",
    async:false
}).done(function() {
 /*      .....
      ..... */
});

another option of course is that within the success , complete or done (depending on your preference) you make the call of each Ajax; for example:

Instead of

 $(function() {
    $.ajax({/* tus opciones link 1 */});
    $.ajax({/* tus opciones link 2 */});
});

Be

 $(function() {
    $.ajax({/* tus opciones link 1 */})
        .done(function () {
            $.ajax({/* tus opciones link 2 */}).done(funcion() {/*....*/});
        });
});

More recently I have tried in some circumstances promise , I have found it useful but I am still in the process of understanding it more thoroughly.

    
answered by 27.05.2017 в 07:04