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

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.

  1. var mp3url = <? php echo "'".$mp3."'"; ?> ;
  2. var refreshIntervalId = setInterval(findURL, 500);
  3.  
  4. function findURL() {
  5.     $.ajax({
  6.         url: mp3url,
  7.         type: 'GET',
  8.         dataType: 'text',
  9.         success: function() {
  10.             jQuery('#loading').append('<br />SUCCESS!!');
  11.             clearInterval(refreshIntervalId);
  12.         },
  13.         error: function() {
  14.             jQuery('#loading ').append('.')
  15.         }
  16.     })
  17. }

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/

  1.  var mp3url = <? php echo "'".$mp3."'"; ?> ;
  2. var refreshIntervalId = setInterval(findURL, 500);
  3.  
  4. function findURL() {
  5.     $.ajax({
  6.         url: mp3url,
  7.         type: 'HEAD',
  8.         dataType: 'jsonp',
  9.         complete: function(xhr, textStatus) {
  10.             if (xhr.status == 200) {
  11.                 jQuery('#loading').append('<br />SUCCESS!!');
  12.                 clearInterval(refreshIntervalId);
  13.             } else if (xhr.status == 404) {
  14.                 jQuery('#loading ').append('.');
  15.             } else {
  16.               jQuery('#loading ').append('whoops, something went wrong. Not sureif MP3 was loaded successfully or not.' + textStatus);
  17.               clearInterval(refreshIntervalId);
  18.             }
  19.         }
  20.     })
  21. }