Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ajax and jQuery to check if file exists - always returns 200 response

So I'm need to check whether a file exists before showing specific data to clients...using jQuery I have this:

<script>
function fileExists(fileLocation) {
    var response = $.ajax({
        url: fileLocation,
        type: 'HEAD',
        async: false
    }).status;
    alert(response);
}
</script>

When I attempt to run the function:

<script> fileExists('http://www.example.com/123.jpg'); </script>

(where example.com is my domain), I ALWAYS receive a 200 response code. I was wondering why this might be happening - could it be that I have a custom error page set through .htaccess? Or, is there a better method to do this?

Note: jQuery 1.5.1 is being used.

Update: It seems it is being directed to our custom error page set through .htaccess:

ErrorDocument 404 http://www.example.com/errors/notfound.php

Not sure if this causes the conflict, or how to get around it.

SOLVED

I checked the headers for my custom 404 page, it was returning a 200 response code. Had to hard code the header:

<?php header('HTTP/1.1 404 Not Found'); ?>

which would then return the 404 response code - fixing my issue.

like image 279
William Orazi Avatar asked Sep 19 '11 15:09

William Orazi


2 Answers

Why don't you realize this asynchronously with the callbacks success and error?

$.ajax({
   type: 'HEAD',
   url: fileLocation,
   success: function(msg){
     alert(msg);
   },
   error: function(jqXHR, textStatus, errorThrown){
     log(jqXHR);
     log(errorThrown);

   }
 });
like image 170
kalyfe Avatar answered Oct 25 '22 04:10

kalyfe


It appeared my issued existed with my custom 404 page, which was returning a 200 status code. I had to hard code the 404 response code using the php header() function, which resolved the issue I was having. Now if the page does not exists it follows correctly:

Using a simple method to test if page/file exists for the moment:

$.ajax({
    type: 'HEAD',
    url: 'http://www.example.com/index.php',
    success: function() {
        alert('Page found.');
    },  
    error: function() {
        alert('Page not found.');
    }
});

Thanks to @kalyfe for the suggestion to switch to async method.

like image 33
William Orazi Avatar answered Oct 25 '22 03:10

William Orazi