views:

1050

answers:

3

I developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.

Is there a way to programmatically determine if a link to a file is broken? If so, How?

Any guide or suggestion is appropriated.

+2  A: 

If the files are not on an external website, you could try making an ajax request for each file. If it comes back as a failure, then you know it doesn't exist, otherwise, if it completes and/or takes longer than a given threshold to return, you can guess that it exists. It's not always perfect, but generally 'filenotfound' requests are quick.

var threshold   = 500,
    successFunc = function(){ console.log('It exists!'); };

var myXHR = $.ajax({
  url: $('#checkme').attr('href'),
  type: 'text',
  method: 'get',
  error: function() {
    console.log('file does not exist');
  },
  success: successFunc
});

setTimeout(function(){
  myXHR.abort();
  successFunc();
}, threshold);
Alex Sexton
A: 

You can $.ajax to it. If file does not exist you will get 404 error and then you can do whatever you need (UI-wise) in the error callback. It's up to you how to trigger the request (timer?) Of course if you also have ability to do some server-side coding you can do a single AJAX request - scan the directory and then return results as say JSON.

DroidIn.net
+4  A: 

If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET method, just HEAD and then check the HTTP status for the expect value (200, or just less than 400).

Here's a jQuery plugin but it didn't seem to do just a HEAD. Instead, here's a simple method provided for a related question:

function UrlExists(url) {
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}
Justin Johnson
I wish I knew how to implement this for the OP's question. Anyone?
Trip
What are you asking?
Justin Johnson