Reputation: 210
So I'm sending an AJAX post request to my server so that I can get information and generate a file. I am able to generate the file and I can even console it in the done function using console.log(data).
I'm just not sure how to go about downloading it; I tried the solution of creating element and using js to click it but it did not seem to work.
Additional info:
I am sending the Ajax request using Jquery. The web application is a python flask application.
Upvotes: 0
Views: 2082
Reputation: 210
This might not be the best way but here's what I had to do, since my version of jquery is not the most update, I had to a save the ajax function into a varible name xhr, to get the response header
success: function (data) {
var disposition = xhr.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
var blob = new Blob([data], {type: 'application/pdf'});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
adapted from https://nehalist.io/downloading-files-from-post-requests/
Upvotes: 1