Javascript Check if File Exists On Server

by Aaron 05/15/08

I have been working diligently on implementing some new features into Velowear.com.  One of these features is an in-page image popup.  Originally I had coded it a an asp.net control within an AJAX panel, but found that this approach was not as flexible as just using pure Javascript.  The only problem was that I wanted to perform some server side checking if the image existed before triggering the in-page popup.  Most of what I had read said this was impossible to do via Javascript, but I knew there had to be a way...

Luckily I stumbled across some Javascript code that uses the XMLHttpRequest Object (this is the core of how AJAX works BTW) that performs this tasks with relative ease.  It uses the XMLHttpRequest object to try and download the file (str) passed into the isFile function.  Supposedly this only works when calling the server that originated the request. 

I hope this helps you out as much as it helped me.


Here is the code:
 

function isFile(str){
    var O= AJ();
    if(!O) return false;
    try
    {
        O.open("HEAD", str, false);
        O.send(null);
        return (O.status==200) ? true : false;
    }
    catch(er)
    {
        return false;
    }
}
function AJ()
{
    var obj;
    if (window.XMLHttpRequest)
    {
        obj= new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        try
        {
            obj= new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch(er)
        {
            obj=false;
        }
    }
    return obj;
}

This code was buried in the middle of the following thread found here:
http://www.codingforums.com/archive/index.php?t-98182.html

Tags:
Category:

blog comments powered by Disqus