learner
learner

Reputation: 73

when and then are not working as expected

Calling AJAX function and wait for AJAX function to be done.

$.when(updateApplication("about_you"))
    .then(function() {
        console.log("when is working perfectly :          ");
    });


function updateApplication(){
    //some code here

    // ajax call update the application and get response back like if applications is updated successfully or not with true/false status.

    return $.ajax({
            type: 'POST',
            url: base_url,
            data: {json: data},
            dataType: 'json'
        }).done( function( data ) {
            return data;
        }).fail({
            return data;    
        });
}

$.when calls AJAX function, AJAX function does its work perfectly but the code inside $.when does not execute. (console.log never prints)

Tried $.when with done

    $.when(updateApplication("about_you")).then(function(){
        console.log("when is working perfectly :          ");
    }).done(function(data){
        console.log("see if it works  :          ");
    });

Still no console.log works, in other words $.when body never execute

another try with when call

    $.when(updateApplication("about_you")).done(function(data){
        console.log("see if it works  :          ");
    });

Still console.log does not print. Any idea what is wrong with calling. What need to fix to able to execute the body of $.when once ajax call finish.

Upvotes: 0

Views: 38

Answers (1)

Syntactic Fructose
Syntactic Fructose

Reputation: 20144

You're already handling the ajax inside updateApplication, you need to remove your usage of done to use when correctly:

function updateApplication(){
  //some code here

  // ajax call update the application and get response back like if applications is updated successfully or not with true/false status.

  return $.ajax({
        type: 'POST',
        url: base_url,
        data: {json: data},
        dataType: 'json'
    });
}

If you still aren't getting any sort of response, you may need to check for failure first before chaining a .then:

$.when(updateApplication("about_you"))
    .fail(function(){ alert('Failed!'); })
    .then(function(){ alert('Success!'); });

Also note that then here might be replaceable with done if you plan on ending the promise chain here. then() is an alias for pipe() and returns a new promise, where as done simply returns a success object that cannot be chained

More info here: jQuery deferreds and promises - .then() vs .done()

Upvotes: 2

Related Questions