Skip to content

Instantly share code, notes, and snippets.

@allanortiz
Created April 11, 2016 20:43
Show Gist options
  • Save allanortiz/ee6dff0695322cc54e3f30b28b47322c to your computer and use it in GitHub Desktop.
Save allanortiz/ee6dff0695322cc54e3f30b28b47322c to your computer and use it in GitHub Desktop.
Download file (PDF) with AJAX.
function downloadFile() {
var blob = "";
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if (this.status == 200) {
blob = new Blob([xhr.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "document.pdf";
link.click();
alert("Nice!");
} else {
alert("Error. Estatus " + this.status + ".");
}
};
try {
xhr.open('POST', 'myurl.php', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = 'blob';
xhr.send('parameter1=&parameter2=');
} catch (e) {
alert(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment