I want to generate a .csv file then download it with AJAX
Insite csv.php I have this code:
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("th.csv","r");
$list = array();
while(! feof($file))
{
$list[] = (fgetcsv($file));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
$list = array_filter($list);
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
?>
so when I'm going to csv.php it makes me download the csv file.
Then inside test.php I have this jQuery code:
$(document).on('click', '#listCSV', function() {
var el = $(this),
csv = el.attr('csv');
$.ajax({
type: 'POST',
url: 'csv.php',
data: {
listCSV: csv
},
success: function(data, textStatus, jqXHR) {
el.html($(data));
}
});
});
But when I'm clicking on #listCSV nothing happens, nothing is being downloaded
Any idea how can I download the csv file when clicking on #listCSV?
when the file is generated just use the file_timestamp.csv location on you're link. so if your file_timestamp.csv is can be accessed via
http://project/csv/file_timestamp.csv
then just link it to a regular link:
<a href="http://project/csv/file_timestamp.csv"/>download csv</a>
Note: if you're not expecting multiple users to generate csv files then just make a temporary file then you can set the link as static. if not just delete every file in the csv folder every 3mins
You need to change header information to output it as download :
$out = fopen("php://output", 'w');
$emails = array();
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="'.$this->filename.'.csv"');
foreach($contacts as $adr) $emails[] = $adr->getEmail();
fputcsv($out, $emails);
fclose($out);
exit;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.