Checking a Url in Jquery/Javascript

That isn’t how AJAX works. AJAX is fundamentally asynchronous (that’s actually what the first ‘A’ stands for), which means rather than you call a function and it returns a value, instead you call a function and pass in a callback, and that callback will be called with the value.

(See http://en.wikipedia.org/wiki/Continuation_passing_style.)

What do you want to do after you know whether the URL is responding or not? If you intended to use this method like this:

//do stuff
var exists = urlExists(url);
//do more stuff based on the boolean value of exists

Then what you instead have to do is:

//do stuff
urlExists(url, function(exists){
  //do more stuff based on the boolean value of exists
});

where urlExists() is:

function urlExists(url, callback){
  $.ajax({
    type: 'HEAD',
    url: url,
    success: function(){
      callback(true);
    },
    error: function() {
      callback(false);
    }
  });
}

Leave a Comment