MissCoder87
MissCoder87

Reputation: 2669

Checking if a file exists

I'm trying to see if a local file exists when a link is clicked, but it always says it doesn't exist. Can anyone spot a glaring mistake i've made?

Thanks

jQuery(document).ready(function() {
   jQuery("a").click(function(){

   var href = jQuery(this).attr('href');

   jQuery.ajax({
       url:href,
       type:'HEAD',
       error: function() {
          alert(href);
       },
       success: function() {
           alert('Huzzah!');
       }
   });
});

Upvotes: 4

Views: 4300

Answers (2)

egig
egig

Reputation: 4430

Ajax can not be performed with file:// protocol. Since you are using Phonegap, there is built in object to used to check if file exist or not: http://docs.phonegap.com/en/1.3.0/phonegap_file_file.md.html#FileReader

How to check a file's existence in phone directory with phonegap

var reader = new FileReader();
var fileSource = <here is your file path>

    reader.onloadend = function(evt) {

        if(evt.target.result == null) {
           // If you receive a null value the file doesn't exists
        } else {
            // Otherwise the file exists
        }         
    };

    reader.readAsDataURL(fileSource);

good luck !!

Upvotes: 2

If you are trying to access a file on your local file system, this is probably blocked by your browser because of Same Origin Policy.

One simple way to get around this is to run a local HTTP server.

e.g. if you have python installed, just run

python -m SimpleHTTPServer

Upvotes: 2

Related Questions