Reputation: 3162
I have two different function()
and a hide loading message one.
function functionOne(){
$.get(baseURL + 'xml/', function(one) {
...
});
}
function functionTwo(){
$.get(baseURL + 'xml/', function(one) {
...
});
}
function hideLoading(){
$('#loading').fadeOut('slow', function() {
$('#loading').hide();
});
}
Now, what I am trying to do is to load them one by one. So I want to call functionTwo
after functionOne
is loaded and hideLoading
after functionTwo
is loaded. This bit of code doesn't work because it hides the loading message before functionOne
and functionTwo
is loaded:
$('.featuredImage').live('click', function() {
functionOne();
functionTwo();
hideLoading();
});
Somebody can help me with this?
Upvotes: 0
Views: 91
Reputation: 18078
$.get()
returns a Promise-compliant jqXHR object.
Returning the jqXHRs from functionOne()
and functionTwo()
will allow you to form a .then()
chain, as follows :
function functionOne(){
return $.get(baseURL + 'xml/');//returns a jqXHR object
}
function functionTwo(){
return $.get(baseURL + 'xml/');//returns a jqXHR object
}
function hideLoading() {
$('#loading').fadeOut('slow');
}
$(document).on('click', '.featuredImage', function() {
functionOne().then(functionTwo).then(hideLoading);
});
Doing it this way keeps functionOne()
and functionTwo()
free of assumptions about what should happen next. All the sequencing logic is in the calling function.
Callbacks can be reinserted into the $.get()
expressions. Providing they do not cause an uncaught error to be thrown, they will not inhibit the sequence.
Upvotes: 1
Reputation: 144699
That's because Ajax is Asynchronous, you should call the functions within Ajax's callback function. Also note that live
method is deprecated, you can use on
method instead.
$(document).on('click', '.featuredImage', functionOne);
function functionOne(){
$.get(baseURL + 'xml/', function(one) {
functionTwo();
});
}
function functionTwo(){
$.get(baseURL + 'xml/', function(one) {
hideLoading();
});
}
Upvotes: 2
Reputation: 178215
Add the next function to the end of the callback
function functionOne(){
$.get(baseURL + 'xml/', function(one) {
...
functionTwo();
});
}
Upvotes: 2