1

I have this code which works perfectly to test whether a specified URL is valid or not

$.ajax({
    url:'test.pdf',
    type:'HEAD',
    error: function()
    {
        console.log("Doesn't exist");
    },
    success: function()
    {
        console.log("exists");
    }
});

My problem arises when I try to turn this into a function by doing this

function URLExists(URL) {
    var exists = false;
    $.ajax({
        url:URL,
        type:'HEAD',
        error: function()
        {
            console.log('false');
            exists = false;
        },
        success: function()
        {
            console.log('true');
            exists = true;
        }
    });
    console.log('returning ' + exists);
    return exists;
}

I can't just do return true and return false from within the error: and success: because it would only return in that function, not the URLExists() function. All the answers I saw when I googled it were to return the nested function, however I can't seem to do that here. When I tried doing it as posted above where I change a variable, URLExists() returns before the variable changes (at least a full second before). I'm sure there is probably some rather simple way to do it, this is just unfamiliar to me.

Mark R
  • 337
  • 2
  • 9
  • Look at the accepted answer for this question: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Guilherme Sehn Jul 24 '17 at 20:08

0 Answers0