Quick (and hopefully easy) question: I need to trigger a download of a PDF file that's generated by a PHP file. I can do this:
<a href="download.php">Download</a>
but should I be doing this another way? Javascript maybe? The above works but the window shows "Loading..." until the download starts. I'd like to provide some feedback to the user that something is happening.
Ideas?
Note: I already have the code that sends the file from the server. It works perfectly. This question is simply about how best to call that script from the client.
Some sites have downloads that automatically start. How do they do that?
The problem with a direct URL is that if the PHP script errors it'll replace th econtent of the existing page, which is not what I want.
To trigger a file download on a button click we will use a custom function or HTML 5 download attribute. The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded.
The readfile() function is used in PHP script to forcibly download any file of the current location, or the file with the file path.
EDIT
Yes javascript, something like:
<a href="download.php" onclick="this.innerHTML='Downloading..'; downloadPdf(this);">Download</a>
If you need to actually understand when the download is started you probably need to call an iframe and then use the "onload" event on it.. for example:
// javascript
function downloadPdf(el) {
var iframe = document.createElement("iframe");
iframe.src = "download.php";
iframe.onload = function() {
// iframe has finished loading, download has started
el.innerHTML = "Download";
}
iframe.style.display = "none";
document.body.appendChild(iframe);
}
The solution you have for download is fine. You may want to consider some visual feedback to the user, perhaps by using javascript to show a "Downloading, please wait message" on the current page when the link is clicked via an onclick handler. Or simply indicate that the download may take some time to start next to the link. Since IE will unload the page, stopping any GIF animations, I prefer text indications for file downloads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With