开发者

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.


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);

   }
 });


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.


What about $.get, which is just a shorthand for jQuery Ajax?

// this file exists
$.get('https://upload.wikimedia.org/wikipedia/commons/7/75/Woman_mechanic_working_on_engine_%28cropped%29.jpeg')
  .done(() => {console.log('file exists')})
  .fail(() => {console.log('File does not exist')}
)

// this file does not exist
$.get('https://example.com/inexistent.jpg')
  .done(() => {console.log('file exists')})
  .fail(() => {console.log('File does not exist')}
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The nice thing here is that the browser fetches the image in the browser, thus you don't need to load it twice when you use it, for example, for html tag img. Here na example:

$('#myButton').click(()=>{

  let imgUrl = $('#imgUrl').val();
  
  $.get(imgUrl)
  .done(() => {
    $('img').attr('src', imgUrl);
    $('#imgText').text('');
  })
  .fail(() => {
    $('#imgText').text('Image does not exist');
    $('img').attr('src', '');
  })

})
img {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Image url: <input type="text" id="imgUrl" value="https://upload.wikimedia.org/wikipedia/commons/7/75/Woman_mechanic_working_on_engine_%28cropped%29.jpeg"><br>

<button id="myButton" type="button">click here to load image</button>

<div id="imgText"></div>
<img>


Async/Await Function

This is kind of a modern way to do this. I was looking to find the best future proof workaround for the depreciated synchronous XHR and AJAX.

Personally I need security so certain files are unavailable to the public. This means that a client side function just wont work. I need a server-side script to check if these files exist.

I've looked around and had a hard time finding this for what I needed it to do. There are well documented other uses, but this one helped me and can be used as another way to solve the OP's question/problem.

async function fetchAsync (q) {
  // await response of fetch call 
  // Your file now can get the file name to check via server side if it is there.
  let response = await fetch('https://yoursite.com/check_exists.php?'+q+(q==''?'':'&')+'time='+(new Date().getTime()));
  // only proceed once promise is resolved
  let data = await response.json();
  // only proceed once second promise is resolved
  return data;
}
var myFilePath = 'images/dingle.gif';
// trigger async function
// log response or catch error of fetch promise
fetchAsync('filepath='+myFilePath+'')
    .then(data => {
                 //
                 console.log(data.myJsonVar);
           if(data.myJsonVar == 1){ // the php file should check and return {"myJsonVar":1} if it found the file in question or {"myJsonVar":0}
                // Run scripts or functions about here...
                // For me it is to check if the file exists before an upload.
                // This saves the upload from failing after it is uploaded because it is a duplicate.
           }else{
                 // I run my upload script and functions
           }

     }
})
.catch(reason => console.log(reason.message))

I want to point out that you can have any number of variables in the json response from the PHP file. However the smaller amount the better as always.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜