views:

1967

answers:

5

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.

+1  A: 

fake it by using an onclick event handler to show a spinning gif

<a href="download.php" onclick="ShowDownloading();">Download</a>
Al W
+4  A: 

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);
}
Luca Matteis
+1 for working code (by the looks of it ...)
benlumley
You shoud return false to disable the link.
Gumbo
+2  A: 

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.

tvanfosson
+1  A: 

Automatically starting downloads usually use a meta tag inside a normal page:

<META HTTP-EQUIV="REFRESH" CONTENT="10.0;URL=download.php">

This example will redirect the browser in 10 seconds to download.php.

Karsten
A: 

I'm having a similar issue, and I tried doing what sktrdie said but the problem is that the load event of the iframe is not triggered when the Save as.. popup appears. When loading other contents (text/html) in the iframe the load event is triggered correctly.

Any ideas on why this occurs?