Reputation: 779
I have a main page containing a number of sections. Each of these sections defines a (document).ready event, calling a function. The function is unique, and defined within the section itself. E.g.
Main.htm
section1 :Defines funcABC(). (document).ready calls funcABC();
section2 :Defines funcDEF(). (document).ready calls funcDEF();
section3 :Defines funcXYZ(). (document).ready calls funcXYZ();
etc..
So the page loads, and each section calls the function it needs, and everything works.
The page has now been changed to load the sections via AJAX (jquery.load()). The layout shown above no longer works as (document).ready only fires when Main.htm loads, but not the sections have loaded.
Main.htm can't call the functions in the sections as it doesn't know which each section needs, and doesn't have the definitions (which are dynamically generated in each section).
I know the design is strange, it's something I've inherited and have to work with..
I basically need each section to its own function after it loads, as it was doing. How can I make this work?
Upvotes: 0
Views: 99
Reputation: 77118
(document).ready
is a handler for the event when you load the DOM, however, you trigger some AJAX events and you want to execute a function when the event finished successfully. The functions executed when the server responded are called callback functions. Let's suppose you have a function, like this:
function() myFunction {
//...
}
you want myFunction
to be executed as a callback function. Let's suppose you use a jquery.load
, like this:
$( "#result" ).load( "ajax/test.html", function() {
myFunction();
});
This is an event handler, which sends a request to "ajax/test.html"
and when response has arrived, executes an unnamed function passed as parameter. This unnamed function calls myFunction
.
Upvotes: 1
Reputation: 839
If I understand correctly, you have multiple AJAX calls and would like to do something after they've all finished. This has nothing to do with the jQuery(document).ready() which is related to the loading of the DOM. It's your application's logic.
A bare-bones solution (a bit ad-hoc) would be as follows:
If you're using jQuery.ajax()
calls, they all have the done
/fail
/always
callbacks you can use to notify some other function that they're done (if you're not using jQuery.ajax
, then find the relevant hook/callback and adjust the code example below accordingly).
Then you could do something after 3 ajax calls have finished:
.
function ABC(){
$.ajax({url:'...'}).always(waitForThemToFinish);
}
function DEF(){
$.ajax({url:'...'}).always(waitForThemToFinish);
}
function GHI(){
$.ajax({url:'...'}).always(waitForThemToFinish);
}
var finished = 0;
function waitForThemToFinish(){
if (finished < 3) { // To ensure that the operation below is called only once
finished++;
if (finished >= 3) {
// do something after some 3 ajax calls have finished
}
}
}
Upvotes: 0