Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Scope Issue

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!

like image 546
Ryan Avatar asked Jul 25 '26 05:07

Ryan


2 Answers

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.

like image 163
Yi Jiang Avatar answered Jul 26 '26 20:07

Yi Jiang


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,
...
like image 45
The Scrum Meister Avatar answered Jul 26 '26 20:07

The Scrum Meister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!