I looked at many sources, but I still can't get it to work. I want to click a link in html and get a text file (e.g. csv).
<button type="button" id="csvButton" class="genericButton"><a id="csvAnchor">Create CSV File</a></button><br/>
Then in javascript:
function getCSVText(evt) {
if (currentChecklistCountry) {
$.post('../php/sendCSV.php',
{
country : currentChecklistCountry,
},
function (data, textStatus, jqXHR){
}
)
.fail(function() { console.log("error in sendCSV.php"); })
.always(function() { console.log("sendCSV.php finished"); });
}
else checklistCountryButton.classList.add("needsAttention");
}
}
Since the a.download or a.href methods are commented out only in Edge and Chrome, I am trying to do this with php.
And php:
<?php
// set_time_limit(0);
// ignore_user_abort(false);
// ini_set('output_buffering', 0);
// ini_set('zlib.output_compression', 0)
ini_set('display_errors', '1');
error_reporting(E_ALL | E_STRICT);
$country = $_POST['country'];
// echo "country = " . $country;
if (!isset($country)) { echo "failure"; exit; }
// echo "after isset";
$fileName = '../Countries/' . $country . 'CSV.txt';
// echo "fileName = " . $fileName;
if(file_exists($fileName)) {
// header("Content-Type: text/plain");
header("Content-type: application/octet-stream");
// header("Content-Disposition: attachment; filename=" . $country . "CSV.txt");
header("Content-disposition: attachment;filename="'. basename($fileName).'"' );
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
else {
echo "file does not exist : " . $country;
}
?>
It just fails, no error messages on the server or console. Data is returned in ajax functions, but this is not in the form of a file upload.
Thanks.
[EDIT] Vir is right. With this modification in the js file, it works:
var form = $('<form method="post" action="../php/sendCSV.php?country=' + currentChecklistCountry + '"></form>');
$('body').append (form);
form.submit ();
form.remove ();
Many thanks.
source
share