PDA

View Full Version : jQuery Ajax call after success function


mberkom
03-30-2009, 11:15 PM
This problem is solved and no longer needs any help.

I have this code and am experiencing some problems

$.ajax({
url: this.html_url,
cache: false,
success: function(html){
$('body:last-child').append(html);
return true;
}
});
doSomething();


My problem is that doSomething is called before the ajax success function has completed. I would like doSomething to be called immediately after the ajax call is completed including the success function. Any help?

Eldarrion
03-30-2009, 11:40 PM
If memory serves me right... the success part of jQuery's ajax is a callback, so....


$.ajax({
url: this.html_url,
cache: false,
success: function(html){
$('body:last-child').append(html);
doSomething();
return true;
}
});


Should achieve the desired result.

mberkom
03-31-2009, 12:55 AM
For various reasons I am unable to do as you suggest. I am writing this code in the context of object oriented jquery and this ajax call is part of a method of the object "Box". The "doSomething" function requires access to the variables of the object which for some reason are made undefined by that ajax call. This caused me trouble for a while until I randomly put "return true;" in the success function. This solved my inability to access the object variables but then stopped me from being able to call my "doSomething" function in the success part of the ajax call. When I call it outside of the ajax then it executes before the ajax and is unable to access any of the newly loaded html. Do you see my problem? If not I may spend some time putting all my files up here and a detailed explanation of what I am trying to create.

Eldarrion
03-31-2009, 03:34 PM
I guess you could try the following:


$('body:last-child').bind('ajaxSuccess', function() {
doSomething();
})


Should probably work, ajaxSuccess being a global event, but eh... other than that... JS will always first complete everything in the first level of actions before going deeper, unless what you need to do is linked to a callback of sorts.