Reputation: 181140
I've looked at a lot of sources on this but I still can't get it to work. I want to click a link in html and have it get a text file (happens to be 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){
// console.log("PHP : sendCSV.php");
// console.log("sendCSV.php, data = " + data);
}
)
.fail(function() { console.log("error in sendCSV.php"); })
.always(function() { console.log("sendCSV.php finished"); });
// var a = document.getElementById("csvAnchor");
// download attribute only currently (12/4/2015) works in Chrome and Edge
// a.href = "Countries/" + currentChecklistCountry + "CSV.txt";
// a.download = currentChecklistCountry + "CSV.txt";
// a.target = "_blank";
// a.href = "../php/sendCSV.php?country=" + currentChecklistCountry + "";
}
else checklistCountryButton.classList.add("needsAttention");
}
}
Because the a.download or a.href methods commented out only work in Edge and Chrome I am trying to do this with php.
And the 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 silently, no error messages on the server or console. Data is returned in the ajax function, but is isn't in the form of a file download.
Thank you.
[EDIT] Vir is correct. 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 ();
Thank you very much.
Upvotes: 1
Views: 305
Reputation: 652
Ajax is not supporting downloads (triggering the save dialog). The best you can do is to create temporary form DOMElement, attach it to document's body, trigger it's submit method and finally remove it from DOM tree. Something like this:
var form = $('<form method="post" action="../php/sendCSV.php"></form>');
$('body').append (form);
form.submit ();
form.remove ();
Upvotes: 1