Test if a File or URL Exists or Check Last Modified Date

Jim Ley writes a very in-depth article about using Ajax calls to test the validity of URLs, test for file existence, or check last-modified dates of files.

While the benefits of checking last-modified dates and testing for a valid URL are probably pretty obvious, making an Ajax call to check if a file exists might seem trivial, since you’re still making an HTTP Request, right?  Well, consider an app that uploads files to a server, what if you wanted to offer your users protection against overwriting existing files?  Jim’s method offers that protection, but by only fetching the <head> of the file, rather than having to download the entire file, saving a good chunk of bandwidth.

A brief of Jim’s article…

Another simple use is finding if a URL exists, in HTTP there are various status codes returned by both HEAD and GET requests, 200 means success, 404 means failure, and the others mean other things. See HTTP status codes for a full explanation. using the status property of the xmlhttp object provides you this status
xmlhttp.open("HEAD", "filename.html", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("URL Exists!")
} else if (xmlhttp.status==404) {
alert("URL doesn't exist!")
} else {
alert("Status is "+xmlhttp.status)
}
}
xmlhttp.send(null)

Happy fetching,
Atg

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.