1

Without using any server-side language, I'm trying to use JavaScript to check if a file exists in a folder (on the same domain, nothing cross-domain): if so, load it; if not, load another one. My code below however doesn't work, for some reason it never seems to enter the second case (file not found, load another page, in this case photoredirect.html): instead, it always tries to load the page which in fact doesn't exist. Thank you for your help!

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script type="text/javascript">

var today = new Date();
var displayDay = today.getDate();
var displayMonth = today.getMonth();
var displayYear = today.getFullYear();

var checkFor = "photos/photo_" + displayYear + displayMonth + displayDay + ".html";

$.ajax({
    type: 'HEAD',
    url: checkFor,
success: function() {
        // page exists
    location.href=checkFor;
},
error: function() {
        // page does not exist
    location.href="photosredirect.html";
}
});

</script>
seb
  • 33
  • 10
  • What kind of error you get when the file does not exists? Please show us the response you get on success on both cases (file exists and file doesn't exists) – Marcelo The Mage Coder Feb 03 '20 at 12:41
  • In both cases, the output is the same file checkFor trying to load, whether it exists or not. Not sure why my question was marked as duplicate with another one at the answers on the other question don't seem to correspond to my issue here... – seb Feb 03 '20 at 16:18

0 Answers0