Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a Url in Jquery/Javascript

All I need is a method that returns true if the Url is responding. Unfortunately, I'm new to jQuery and it's making my attempts at writing that method rather frustrating.

I've seen several examples of jQuery using .ajax, but the code is consistently failing on me. What's wrong?

var urlExists = function(url){
    //When I call the function, code is still executing here.
    $.ajax({
        type: 'HEAD',
        url: url,
        success: function() {
            return true;
        },
        error: function() {
            return false;
        }            
    });
    //But not here...
}
like image 722
user474632 Avatar asked Nov 29 '10 08:11

user474632


2 Answers

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, 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 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);
    }
  });
}
like image 59
Han Seoul-Oh Avatar answered Sep 22 '22 18:09

Han Seoul-Oh


urlExists() can not return because it needs wait for the request.

Either pass it a callback, or make it synchronous (not recommended, because it locks the browser).

var urlExists = function(url, callback) {

    if ( ! $.isFunction(callback)) {
       throw Error('Not a valid callback');
    }   

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

};

Then you can do

urlExists('/something', function(success) {
    if (success) {
        alert('Yay!');
    } else {
        alert('Oh no!');
    }
});

It also worth mentioning the same origin policy.

Also, returning from an anonymous function's scope will not return in the parent function (like in your original example). It just returns that inner function. To return from an inner to a parent, set a flag and return it.

like image 35
alex Avatar answered Sep 20 '22 18:09

alex