0

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.

2
  • could you post loadChildNodes function too? What does it return? Commented Aug 29, 2012 at 12:07
  • You might have to use a callback for this, does loadChildNodes($element) returns anything? can you post the code of this method? Commented Aug 29, 2012 at 12:08

4 Answers 4

2

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...)

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

2 Comments

Then i think you will need to return the ajaxObject from loadChildNodes - right?
That's right, and you can then execute any success handlers attached to the ajaxObject. But be warned that success() is being deprecated in favour of done() see api.jquery.com/jQuery.ajax
1

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"); }); }); 

Comments

1

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 }); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.