Vancouver Web Consultants

May 1, 2009

Triggering File Downloads with Mootools

Filed under: Mootools, Tutorials — Tags: , — Nelson @ 6:37 am

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:

<p>[<a href="my-fictional-download-script.php" id="download" target="_blank">download a file</a>]</p>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if($('download')){
	var myFrame = new Element('iframe', {
		src: 'about:blank',
		id: 'myFrame',
		styles: {
			'visibility': 'hidden',
			'display':    'none'
		}
	}).injectInside(document.body);
	$('download').addEvent('click', function(e){
		e.stop(); 
		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:

1
2
3
4
5
6
7
8
9
10
$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;
exit;

2 Comments »

  1. Excellent script… i was having some problem trying to ajaxify my downloads, and i think your script is simple, clear, and easy to deploy.

    Thanks for sharing this :)

    Comment by Damien — July 21, 2009 @ 12:56 am

  2. [...] previously posted this method for Mootools, and now here it is for [...]

    Pingback by Triggering File Downloads with jQuery - Vancouver Web Consultants — November 9, 2009 @ 11:58 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress