views:

411

answers:

5

On the client side using jQuery, I want to know if I can just check if a link URL is valid (i.e. doesn't return a 404). This link points to another domain, so if I just use $.get() then I end up with a permission issue. I remember reading something about using a JSONP request, but I don't remember.

+1  A: 

JSONP works if the server you are calling on can return JSONP formatted response. Which basically means a script that calls a callback function on your page after getting loaded. see http://en.wikipedia.org/wiki/JSON#JSONP

In your case it won't work unless the other site is willing to cooperate or you have a proxy script on your own site.

If you want your script to work with sites not under your control, your best bet will be to use a proxy or a iframe hack.

Tahir Akhtar
A: 

You can't make a request like that to another domain. That is a security feature in the browser. You may have to try doing something in an iframe or something and checking that.

Jage
A: 

I found a solution that seems to work (using YQL):

$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
            "q=select%20*%20from%20html%20where%20url%3D%22"+
            encodeURIComponent(url)+
            "%22&format=xml'&callback=?",
    function(data){
      if(data.results[0]){
        // do whatever
      } 
    }
  );

Assumes the URL you want to check is in the variable 'url'.

Scott Whitlock
From the docs at http://api.jquery.com/jQuery.getJSON/ :If the specified URL is on a remote server, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
Tahir Akhtar
A: 

JSONP is the true solution when you have the ability to change or have the code changed. Without it you need to either proxy the request to your server. Or you can use a method like this

http://flxhr.flensed.com/demo.php

sberry2A
A: 

jsonp wont do you much...

What you should do is create a local proxy easily on your server using your favorite language that'll simply load the url you pass to it and return the response code. Then, use jquery ajax to load up the proxy page with the url you want to test.

Ariel
I don't have the option of the local proxy unfortunately (I only have certain customization options available on the server - some custom HTML places, and I can load JavaScript)..
Scott Whitlock