DEV Community

Syed Saadullah Shah
Syed Saadullah Shah

Posted on

Triggering File Downloads with Mootools

Creating a javascript links that uses AJAX (or, more accurately, an asynchronous http request) to trigger a file download, usually results in disappointment. Headers returned by a PHP script called asynchronously do not trigger a download in the browser.

If you want to have a link to a file download that does not cause a page refresh or opening a superfluous browser window in order to make a file download happen, it's actually quite easy with only a few lines of JS. There's no "AJAX" here, but it sure feels like it. The method relies on adding an invisible iFrame to the DOM, and simply loading the script triggering the download into that iFrame:

[download a file]

var myFrame = new Element('iframe', {
src: 'about:blank',
id: 'myFrame',
styles: {
'visibility': 'hidden',
'display': 'none'
$('download').addEvent('click', function(e){
myFrame.src = this.href;
Now as long as your PHP file is configured to return the correct headers for the file type you would like downloaded, this should trigger a download. Here's an example of some PHP to download a .csv file:

$filename = 'download.csv';
//this is where you would format your data, selecting and looping through rows from your database for example.
//here we just output one line:
$out = "this, is, a , csv\n";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;

Discussion (0)