Aaron A
Aaron A

Reputation: 543

Javascript check if a site url is accessible

I'm trying to come up with the best jquery method to check to see if a site url is accessible. All I need to do is confirm that the user can access the site. However, with CORS i'm not quite sure of the best way to do this. I've been trying this but running into issues.

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

But I'm getting the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my-site.com. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

What's the best way to accomplish this?

Thanks!

Upvotes: 0

Views: 2047

Answers (3)

Nourhan Ahmed
Nourhan Ahmed

Reputation: 179

you can use`

function UrlExists(url, cb){
            jQuery.ajax({
                url:      url,
                dataType: 'text',
                type:     'GET',
                complete:  function(xhr){
                    if(typeof cb === 'function')
                       cb.apply(this, [xhr.status]);
                }
            });
        }

        UrlExists('-- Insert Url Here --', function(status) {
            if(status === 200) {
                -- Execute code if successful --
            } else if(status === 404) {
                -- Execute code if not successful --
            }else{
               -- Execute code if status doesn't match above --
            }
        });

Upvotes: 0

OO7
OO7

Reputation: 690

You can try to add crossDomain property with value true, also initialize support cors by true.

$.support.cors = true;

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

Upvotes: 0

Brad
Brad

Reputation: 163602

Due to cross-origin restrictions, you won't be able to do this client-side. You'll have to have some service running server-side.

Upvotes: 1

Related Questions