The.Anti.9
The.Anti.9

Reputation: 44738

jQuery: Waiting for callbacks to return before continuing

I have a page which uses a fair bit of ajax to load its contents when various things are clicked and right now I am working on being able to link to the different parts of the page by reading the incoming hashes in the url as a sort of path. I figured that I could just go through the different sections of the hash that comes in and trigger the right clicks using jQuery's .trigger(). The problem in doing this is that the next second trigger will be called before the contents of the section is actually loaded (as it is being loaded via ajax) meaning the thing it is trying to trigger doesn't exist. Is there a good way to set sort of a flag or something to know when all the callbacks complete and all of the content is loaded before I use the next trigger? Or am I approaching this the completely wrong way? Just looking for some general strategy on how to get this done.

Upvotes: 0

Views: 514

Answers (2)

Valerij
Valerij

Reputation: 27758

how about using the

$.ajax({
  url: 'ajax/test.php',
  async:false
});

to wait until request is loaded

Upvotes: 1

mVChr
mVChr

Reputation: 50215

You want to create a success callback. As the name implies, this code will be executed once your load has completed successfully.

$.ajax({
  url: 'ajax/test.php',
  success: function(data) {
    // your code to execute after load is complete
    // data parameter contains any information returned from test.php
  }
});

See "Callback Function Queues" on http://api.jquery.com/jQuery.ajax/

Upvotes: 2

Related Questions