sonam
sonam

Reputation: 3760

Calling other functions only after getting result from ajax call in jquery

Here is my function:

loadChildNodes($('#budgetline' + id));
$('.child-of-budgetline' + id).each(function(){
    $(this).expandTreeNode();
    console.log("test");
});

loadChildNodes($element) function makes an ajax call. I want to wait until this function is completed and then only execute the lines after it. But doesnot happen so. How can i make the other lines execute only after the function loadChildNodes has completed.

Upvotes: 0

Views: 120

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

use a promise available by deferred objects:

$.when(loadChildNodes($('#budgetline' + id))).done(function() {
    $('.child-of-budgetline' + id).each(function(){
       $(this).expandTreeNode();
       console.log("test");
    });
})
.fail(function() {
   /* some errors occured */
})

To properly work loadChildNodes() should return either a promise (to resolve on ajax success callback and reject on error callback) or the ajax object itself ($.ajax or other shortcut, like $.get, $.post...)

Upvotes: 2

adeneo
adeneo

Reputation: 318182

You'll need to return the ajax call as an object :

loadChildNodes($('#budgetline' + id)).done(function() {
    $('.child-of-budgetline' + id).each(function(){
        $(this).expandTreeNode();
        console.log("test");
    });
});

function loadChildNodes(elem) {
    return $.ajax({

       //do ajax
    });
}

Upvotes: 1

sundar
sundar

Reputation: 1760

Introduce a callback parameter for loadChildNodes and call that callback in the success callback of ajax call inside that method.
Now refactor your code in way that the remaining lines of code will be moved to callback and passed to loadChildNodes method.

loadChildNodes($('#budgetline' + id), function() {
   $('.child-of-budgetline' + id).each(function(){     
     $(this).expandTreeNode();     
     console.log("test"); 
   }); 
}); 

Upvotes: 1

danwellman
danwellman

Reputation: 9253

Use $.when().then() to do stuff once AJAX completes, e.g:

$.when(loadChildNodes($('#budgetline' + id))).then(function() { 
    //stuff 
});

Upvotes: 1

Related Questions