I am trying to make a JS link POST to another php file to cause a csv download. Everything is happening correctly - except for the csv download. I can see the csv data in DevTools in chrome, but the csv is not downloading.
The link has target _blank.. I don't know where to put _blank in the JS.
I know that I can do this easily with GET (without JS), but I'd like to do this with POST.
PHP:
<a id="data-download" target="_blank" data-toggle="tooltip" data-placement="left" title="Export to Excel">
JS:
$("#data-download").on("click", function(e){
$.post("XL.php", { e: "<?php echo $e?>", time: "2pm" } ); //Your values here..
});
Form Processor:
$filename = "Ensemble-D$div$ensabbr.csv";
$fp = fopen('php://output', 'w');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
#header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
// output the column headings
fputcsv($fp, array("filename.csv"));
fputcsv($fp, array('column','headings'));
$query = "SELECT a.fields, b.fields FROM entries a, other b ORDER BY something";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_row($result)) {
fputcsv($fp, $row);
}
To use POST and have the file downloaded, one thing you can do is create a html form and make your link submit it.
<form action=XL.php method=post id=export target=_blank>
<input type=hidden name=e value=...etc
</form>
$("#data-download").on("click", function(e){ $('#export').submit() });
You could even create the form in JavaScript to not have to worry about duplicate IDs