I had the same issue and opted for a solution in two steps.
I think this is a good solution to show and hide a spinner.gif and/or waiting message while preparing file until the download is ready to begin.
- First I modifiy my anchor with jQuery to call my download function by ajax bby adding a
?cmd=prepare
on my uri. This will prepare my PDF on server side and store it in a reachable folder by the client (for example domain.ext/documents/my_pdf_name.pdf).
HTML (bootstrap 3) :
<a href="/search/download" class="btn btn-primary pull-left download">
<i class="fa fa-file-pdf-o"></i> Download result in PDF
</a>
jQuery :
$(function() {
$('.download').on('click', function(e) {
e.preventDefault();
$('.loading').show();
url = $('.download').attr('href') + '?cmd=prepare';
$.ajax({
url: url,
type: 'get',
success: function(filename) {
console.log(data);
window.location = filename;
$('.loading').hide();
}
});
});
});
PHP server side :
// ajax call
if(addslashes($_GET["cmd"]) == "prepare") {
echo create_pdf($_SESSION["search"], $out="prepare");
die();
}
- When file is ready the function
create_pdf()
will return filename to client and, on my success function in ajax query, I call a window.location = filename
that show me the "save as window".
The preparation of the document on server side is called by ajax, but the download is not !
- The problem resulting of this solution is storage of files you don't want to keep on server. So you can delete files older than x hours with a bash script. For example https://stackoverflow.com/a/249591/2282880