How to check if a file exists using JQuery

The best way to do this is with an AJAX HEAD request. HEAD requests only ask for and return the header from the destination file, so they’re much faster than POST or GET requests. Perfect for a simple file check.

It’s also worth noting that a HEAD request also returns the content length and last modified date, and that jQuery has an “ifModified” option for the .ajax function that returns a boolean value.

Quick code snippet:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error:
        function(){
            //do something depressing
        },
    success:
        function(){
            //do something cheerful :)
        }
});

Couldn’t be easier!

Share and Enjoy:
  • Print
  • Digg
  • Google Bookmarks
  • email
  • StumbleUpon

Date: Wednesday, January 6th, 2010
Category: Web Dev

  • D87manish

    this is always returning success when I am trying to find out if a given url in my local server has a file or not..

  • This works beautifully on iOS. Thanks!

  • Şafak SARAÇOĞLU

    Çok teşekkür ederim uzun zamandır aradığım bir fonksiyondu - Thanks

  • Jay Kelkar

    This only works if the file is on the same server that served the javascript code.

  • Jeremy084

    How would I show the Last Modified date of a file?

  • Worked like a charm.  Simple and elegant!   Ran in Firebug.

    Thanks

  • I get "
    XMLHttpRequest cannot load http://my.server.net/blablabla.... Origin null is not allowed by Access-Control-Allow-Origin." in the Chrome debug window.

    So does this mean the file you want to check must be on your own server (that is: where the HTML file came from)? In other words: you can not check a file on another webserver?

  • JTB

    nice work, I use it with jQuery 1.7.1 and everything works like a charm

  • Bgaeddert

    Nice!

  • Nand Kumar

    This is always returning Success.

  • Aaa_xxx135

     good u save my times,thanks.

  • Kogepan

    I just tested it and it works perfectly. Try using firebug and checking the console. It should show the HEAD request and return either "200 OK" and "do something cheerful :)" or "500 Interal Server Error" and "do something depressing." If the HEAD request doesn't show up in the console, then there's something else going on. If it always goes to cheerful action, then I wonder if it's a jQuery version issue? I'm using jQuery 1.4.4.

  • Spacer98

    of course it doesnt work, it just goes always to cheerful action

  • Ippel

    why?

  • Coder_emran

    It doesn't work...

  • hdrnt

    cool. thanks for sharing this! I like the comments, especially.

    does it work as well if I want to check if a connection to the internet exists at the moment and only then reload the page with location.refresh(true)?

    will have to check this out when I'm back at my developing unit.. ;)

blog comments powered by Disqus
  • « Older Entries
  • Newer Entries »

Copyright © 2009 Rajeev Singh