File browser + ajax

by Henrik Korsgaard

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<input type="file">
<button id="brokenUploadButton">
  Does not work!
</button>
<button id="customFileUploadButton">
  Works
</button>

CSS

input[type="file"] {
  display: none;
}

#brokenUploadButton {
  background: salmon;
}

#customFileUploadButton {
  background: springgreen;
}

JavaScript

var brokenUploadButton = document.querySelector('#brokenUploadButton');
var customFileUploadButton = document.querySelector('#customFileUploadButton');
var file = document.querySelector('input');

//This does not work due to the securtity features prohibiting initiating the file browser window programmatically 
brokenUploadButton.addEventListener('click', function(e) {
  ajax(function(ajaxData) {
    input.click()
  });
});


//This works because it uses a timeout function as a hack
customFileUploadButton.addEventListener('click', function(e) {
  var returnValueToCheck;
  ajax(function(ajaxData) {
    returnValueToCheck = ajaxData;
  });

  setTimeout(function() {
    if (returnValueToCheck !== undefined) {
      file.click()
    } else {
      console.log("Criteria not fulfilled")
    }
  }, 1000); //Timer should be larger than AJAX timeout
});

function ajax(callback) {
  var xhr = new XMLHttpRequest();
  xhr.timeout = 500;
  url = "/echo/jsonp/";
  xhr.open("GET", url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr.responseText);
    }
  }

  xhr.ontimeout = function(e) {
    console.log("Timed out")
    callback();
  }

  xhr.send();
}