mrdaliri
mrdaliri

Reputation: 7328

jquery.when ajax issue

Let's see my code first:

$.when(function(){
    //blah blah blah...
    $.post('submit.php', {name: 'John'}, function(){
        console.log('saved!');
    }, 'text');
    //blah blah blah...
})
.then( $('#data').show() );

What does it mean? I think it means when first function does its work (post to submit.php and some other works), show the #data. (Am I right?)

But, when I run it, it first shows the #data and then log saved! (means post finished)

Why?

Upvotes: 2

Views: 365

Answers (2)

odupont
odupont

Reputation: 1976

You can make it work like that

$.post('submit.php', {name: 'John'}, function(){
    console.log('saved!');
}, 'text').then( $('#data').show() );

or, if you want to keep using $.when

$.when(function() {
    return $.post('submit.php', {name: 'John'}, function(){
        console.log('saved!');
    }, 'text');
}).then( $('#data').show() );

Upvotes: 0

SLaks
SLaks

Reputation: 887285

You shouldn't be calling .when() at all.
$.post() already returns a Defered object.
You can call .then() on it directly.

Upvotes: 2

Related Questions