Let's say I have download links for files on my site. When clicked these links send an ajax request to the server which returns the URL with the location of the file. What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?
I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.
Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
I'd suggest window.open()
to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
Just call window.location.href = new_url
from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar