3

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!

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But his question about closure brings up a good point, doesn't any assignment without var preceding it assign to global namespace? And if so, his result=true in the anon func assigns to global?
@philwinkle No, anon. functions are ran in the scope of the function that creates them. See a simple test case like: jsfiddle.net/txWLj The engine goes up through each scope looking for the variable until it reaches the global scope.
2

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,
...

1 Comment

There is almost no reason why one might want to use async: false; its mostly a crutch for lazy programmers, given it's effects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.