Reputation: 6866
I'm trying to get this function to work. I think the function is pretty self explanitory:
function FileExists(path){
var result = false;
$.ajax({
url: "http://mydomain.com/"+path,
type: "HEAD",
success:
function(){
result = true;
}
});
return result;
}
I need the anonymous function that is called upon success of the ajax post to set the variable "result" that was defined inside the FileExists function to true so that I can return that value from the FileExists function. I think I need a closure for this but they confuse the hell out of me.
Please help! Thanks!
Upvotes: 3
Views: 109
Reputation: 30111
Ajax calls are by default asynchronous, you can either use a callback function:
$.ajax({
url: "http://mydomain.com/"+path,
type: "HEAD",
success: function(){
callback(true);
}
});
Or make the call synchronously.
$.ajax({
async: false,
url: "http://mydomain.com/"+path,
...
Upvotes: 2
Reputation: 50095
It's not a scoping issue, but rather because $.ajax
is asynchronous, meaning that FileExists
will return
before $.ajax
will complete. What you should be doing is to move all code that depends on result
to inside the success
callback.
Upvotes: 3