Using Javascript/jQuery to check if offsite file exists with given URL

Submitted by Danny on Thu, 10/09/2014 - 15:30

So I needed to see if an MP3 was successfully uploaded to our streaming server, and display the status on our website where our user's access the upload form. However, I ran into some issues with Access-Control-Allow-Origin access headers and with just how to acquire the status code. 

My first solution was just use AJAX to try and get the file. If it fails, then it must not exists and it should continue to look for it. And if it succeds, then it should stop looking for it and print a little confirmation message.

var mp3url = <? php echo "'".$mp3."'"; ?> ;
var refreshIntervalId = setInterval(findURL, 500);
 
function findURL() {
    $.ajax({
        url: mp3url,
        type: 'GET',
        dataType: 'text',
        success: function() {
            jQuery('#loading').append('<br />SUCCESS!!');
            clearInterval(refreshIntervalId);
        },
        error: function() {
            jQuery('#loading ').append('.')
        }
    })
}

That should have worked, right? Not exactly. It always fails, whether or not the file does exists, because the browser doesn't allow XMLHttpRequest from a different domain to try and prevent cross-site-scripting. This is why your browser's error console might say something like, "No 'Access-Control-Allow-Origin' header is present on the requested resource."

However, if we use the jsonp datatype (note the p at the end), we can get away with this. "The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content." - https://learn.jquery.com/ajax/working-with-jsonp/

 var mp3url = <? php echo "'".$mp3."'"; ?> ;
var refreshIntervalId = setInterval(findURL, 500);
 
function findURL() {
    $.ajax({
        url: mp3url,
        type: 'HEAD',
        dataType: 'jsonp',
        complete: function(xhr, textStatus) {
            if (xhr.status == 200) {
                jQuery('#loading').append('<br />SUCCESS!!');
                clearInterval(refreshIntervalId);
            } else if (xhr.status == 404) {
                jQuery('#loading ').append('.');
            } else {
              jQuery('#loading ').append('whoops, something went wrong. Not sureif MP3 was loaded successfully or not.' + textStatus);
              clearInterval(refreshIntervalId);
            }
        }
    })
}