Send csv file from php to browser

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){
      // 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");
  }
}

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.

+1
source share
1 answer

Ajax ( ). , , DOMElement, , , , DOM. - :

var form = $('<form method="post" action="../php/sendCSV.php"></form>');
$('body').append (form);
form.submit ();
form.remove ();
+1

Source: https://habr.com/ru/post/1629361/


All Articles