Good morning all, I need to force download csv file when the user click the button "Export CSV" , i see a lot of page (here and with google) and try a lot of thing but anything is working for me. I have one main page with this button and clicking it send a POST request (with Javascript and ajax) to another page who made the csv file and theoretically do the download of the file. This is the code of the main page:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
</head>
<?php
$filter="<button id='exportCSV' >Export CSV</button><br/></div>";
echo $filter
?>
<script>
$(function() {
$("#exportCSV").click(function(){
var query="select * from thcu_cabtemphpc order by timetag desc limit 300";
var table="thcu_cabtemphpc";
//alert(query+" "+table);
//alert(dataString);
$.ajax({
type: "POST",
url: "exportCSV.php",
data: {cvsExp: query, table:table},
success: function(result){
alert("Export in progress");
//$("#export").html(result);
}
});
});
});
</script>
</html>
Of course this is just a test, i have another main page where the user can select the query and the table. This is the code of ExportCSV.php
<html>
<body>
<?php
include('connection.php');
function array2csv($bd, $query, $id){
$sql = mysql_query($query);
$day = gmdate("d-M-Y");
$offset = +2 * 3600; // timezone offset for UTC-13
$utcTime = gmdate( 'd.m.Y H:i:s' );
$milliseconds ="".round(microtime(true) * 1000);
$val= substr($milliseconds,8,10);
//echo $val;
$valor = gmdate( 'd-m-Y_H-i-s-'.$val, time() + $offset );
$name= $day."_".$id."data_export_".$valor.".csv";
$fp = fopen($name, 'w');
while ($res=mysql_fetch_row($sql)) {
$count = 0;
foreach ($res as $val) {
if ($count == 0){
$data = gmdate("Y-m-d H:i:s", substr(($val/10000000) - 12219292800, 0,10));
$arr[$count] = $data;
$count++;
} else {
$arr[$count] = $val;
}
}
$delimiter=",";
fputcsv($fp,$arr,$delimiter);
}
//fpassthru($fp);
fclose($fp);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $name . '.csv"');
header('Content-Length: ' . filesize($name));
echo readfile($name);
}
if(isset($_POST["cvsExp"])) {
$query=$_POST["cvsExp"];
$id=$_POST["table"];
//download_send_headers("data_export_".gmdate("Y-m-d").".csv");
array2csv($bd,$query,$id);
die();
}
?></body>
</html>
I try the code like this and doesn't work, i try to substite application/octet whit text/csv, i try to insert echo readfile($name) or only readfile($name) but anything work. The result of this is create a file inside the webroot and it's not good, i would like the the browser download the file. Thanks a lot.
EDIT: I try to execute only the page with the download script and it's work, the problem is when i call it with ajax!!! How it's possible? Where is the error?