Seth Duncan
Seth Duncan

Reputation: 1255

Determine if Link is valid upon user clicking on it

I offer a widget where a user can store their links that they have created.

So in other words They:

  1. Click Add Link
  2. Modal Pops up and they enter information: Link Title, Link URL, Order
  3. Saves that to the DB via AJAX and then refreshes the widget to display all of the users links they have created.

What I would like do is when the user clicks on their link, determine if the link exists(Could be not on this domain so I can see a foreseeable issue w/ AJAX) if it does then proceed with normal Open new Window and send them on their merry way.

However if not I would like to generate a Growl Like message that says something like.

I'm sorry that Link Does not exist, please verify your link.

I basically need the method for validating the links existence on a client side basis. Is this even possible ?

Upvotes: 1

Views: 2324

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160862

You could use jquery to attach a click() event handler on all links, that in turn try to load the URL in a hidden iframe, if that succeeds then open the link in a new window. Note that this is a very expensive way of link checking. Maybe something smarter could be done like an HTTP head request.

Edit:

Found the solution (for plain javascript only though) here: HTTP HEAD Request in Javascript/Ajax?

function UrlExists(url)
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

And a jQuery solution came from here: Ajax HEAD request via Javascript/jQuery

ajaxSizeRequest = $.ajax({
    type: "HEAD",
    async: true,
    url: url,
    success: function(message){
    }

As @Matt King pointed out these are actually pretty useless cross domain - in that case I'd set up a proxy.aspx page in your application that you query instead. This proxy would then have to execute the HTTP HEAD request in C#, and return the result (success/failure) to the client/jQuery.

Upvotes: 2

Related Questions