Downloading files with jQuery
Hello all,
I would like to suggest you this article. It explains how to create a “trigger” download with jQuery using temporary forms.
To sum up we have a PHP part (backend is not mentioned in the article):
<?php
$filename = $_POST['filename'].".".$_POST['format'];
header ("Content-Disposition: attachment; filename=$filename");
echo $_POST['content'];
return
and a Javascript part:
jQuery.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
that is triggered with
$.download('/export.php','filename=mySpreadsheet&format=xls&content=' + spreadsheetData );
NOTE: Be aware of the splitter char ” = “, because if you are trying to generate something with ” = ” chars inside the script will not work, then replace:
var pair = this.split('=');
with
var pair = this.split('|'); // what you want
And that’s all for today
No comments yet.