0

I want to edit a javascript variable based on whether or not a file exists. Can this be done using a callback function with an ajax get request? Here is a potential solution based on a suggestion from user Jonathan Crowe:

var url="Content/Features/column1.html";
var url2="";
function getURL2(callback) {
    callback = callback || function() {};

    $.ajax({
            url: url,
            error: function()
            {   
               callback("something");
            },
            success: function()
            {
                callback("something else");
            }
        }); 

}

getURL2(function(url2) {

});

When debugging, url2 = "something" at the end of the

getURL2(function(url2) {

    });

call. However if I try to access url2 outside of this function it is still set to "". How can I change the value of url2 based on the result of an ajax get request?

Thank you very much for taking time to help. Let me know if you need anything else from me.

user95227
  • 1,853
  • 2
  • 18
  • 36
  • 1
    If you have a *parameter* `url2` it will shadow the *global* `url2` inside the function definition. – Dave Newton Feb 19 '15 at 17:55
  • An answer is also here: http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript – TommyRay Feb 19 '15 at 17:56

1 Answers1

0
var url2 = "";
$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    async : false,
    error: function()
    {
        //file not exists
        url2 = "something";
    },
    success: function()
    {
        //file exists
    }
});

// If file does not exists url2 will be equal to something here as well.
void
  • 36,090
  • 8
  • 62
  • 107
  • This creates the typical race condition where `url2` will attempt to be accessed before the async call completes; IMO this isn't a great idea. – Dave Newton Feb 19 '15 at 17:59
  • ... Making it async isn't the correct approach either, almost ever :( – Dave Newton Feb 19 '15 at 18:04
  • Yeah my understanding was using a callback function is a better practice than setting async to false. This is all pretty new to me though. – user95227 Feb 19 '15 at 18:10
  • @user95227 Ideally you'd be doing what you need to in the callback function (or using promises) rather than relying on a global variable, precisely to avoid this kind of situation. – Dave Newton Feb 19 '15 at 18:13