views:

292

answers:

3

How do I check if a file on my server exists in jQuery or Javascript?

Thanks in advance.

+15  A: 
$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

EDIT:

Here is the code for checking 404 status, whitout using jquery

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

Small changes and it could check for error 200 (file exists) etc.

PS. sorry for how it looks, dont know how to paste code, so i use "pre"

cichy
+1. Beat me to it. :)
casablanca
That won't necessarily tell you whether the file exists or not. There is more than one way for an AJAX request to error.
Gareth
I know, connection might be down, etc. This you can also check by checking file that you know for sure exist. But question was about something else ;)
cichy
you should check for the status code===404
Marco Mariani
Yeah, slight improvement would be to check for different status codes inside your error callback method, 404 being the specific one you are referring to, though you probably would care just as much if you got a 500 (internal server error) or a 403 (access denied).
Gabriel
in your pure javascript example you should be binding `OnReadyStateChange` event before you check the HTTP_STATUS.
RobertPitt
The example code is wrong, and there's nothing whatsoever said about what's going on at the server. The original question is pretty vague, but there's no reason to assume that the server that's running there is in fact mapping URLs directly to the file system. Honestly, I don't see why this answer is so popular as it doesn't really say how to do what the question asked for.
Pointy
A: 

Not sure its possible without something serverside going on. It would cause interesting security problems if I could write stuff to interact with your files in javascript. Use PHP for this in my opinion.

jason
+1  A: 

What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.

What type of server are you trying to communicate with? You may need to write a small service to respond to the request.

MadcapLaugher