Mauro Sebastian Aquino Mauro Sebastian Aquino - 2 months ago 7
Ajax Question

Asynchronous jquery - ajax when().then();

I'm new in ajax & jquery and i have been trying to read the documents but i'm having a hard time understanding some concepts:

$.when(function(){

$.ajax({url:'php/Mostrarphp.php', type:'post',data: {queHacer:"MostrarUsuarios"}})
.then(function(success){

$("#main").html(success);

},function(error){

$("#main").html(error);

});
})

.then(function(){

console.log("test");

});


What i'm trying to do is for the first function to go into the php file and inside that file there is only an include to another file. after that i want to have a console log shown. (This is just practice for when i need to run functions that retrieve data and will take longer).

The issue here is that the echo is not showing on the application, only shows what is resolved on the then (console.log("test")).

What is the correct way to have this execute the inside function and then the second one?

Answer

When you use $.when, you are creating a new promise, one that needs to be resolved. Normally, $.when is used to "combine" multiple promises into one and then run a function once all of them resolve.

What you've passed to $.when is just a function. A function that never gets run. From the docs:

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

So, that means your console.log("test"); is ran, but your AJAX code is never ran.

You do not not to use $.when here. $.ajax already returns a promise, there's no need to make another one. You can just chain .then() calls.

$.ajax({
    url:'php/Mostrarphp.php',
    type:'post',
    data: {queHacer:"MostrarUsuarios"}
}).then(function(success){
    $("#main").html(success);
},function(error){
    $("#main").html(error);
}).then(function(){
    console.log("test");
});

EDIT: In the comments you said:

[no] matter how much time the inside execution takes to complete, the outside [should] always execute second

If this is what you want, then you will need to create another promise. You can do that and then have it resolve once your "inside" function is complete. I'd suggest wrapping your AJAX code in a function and having it return a promise that you can attach a callback to.

function ajaxCall(){
    var d = new $.Deferred;

    $.ajax({
        url:'php/Mostrarphp.php',
        type:'post',
        data: {queHacer:"MostrarUsuarios"}
    }).then(function(success){
        setTimeout(function(){
            $("#main").html(success);
            d.resolve();
        }, 2000);
    },function(error){
        $("#main").html(error);
        d.reject();
    });

    return d.promise();
}

ajaxCall().then(function(){
    console.log("test");
});
Comments