Skip to content

Instantly share code, notes, and snippets.

@narenaryan
Last active July 4, 2016 07:47
Show Gist options
  • Select an option

  • Save narenaryan/7dd438c02e65caa0f21db63959e4150c to your computer and use it in GitHub Desktop.

Select an option

Save narenaryan/7dd438c02e65caa0f21db63959e4150c to your computer and use it in GitHub Desktop.
This is a snippet to make a post request to get excel file from server
$("#my-button").on("click", function(){
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(result));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment