Jannis
Jannis

Reputation: 107

How to download a csv file with Javascript and AJAX on a specific button?

I am generating a CSV string with PHP and send it via AJAX to my Javascript function.

A simple button

<button id="download" type="button" onclick="csvExport()" name="button">CSV</button>

Call that function and should download a CSV file from the string. How can I handle that?

My PHP Function

function exportCSV(){
$profs = $this->getAllDozent();
$profs = json_decode($profs, true);
$currentID = 0;
$csv = "IDDOZENT,IDVERANSTALTUNG,BEZEICHNUNG,SWS,CREDITS,HAEUFIGKEIT_PA,FAKTOR_DOPPELUNG,SOMMER,WPF,KOSTEN_PA,\n";

// Iteriere durch Professor Array
foreach($profs as $key => $value){
  $currentID = $value['IDDOZENT'];

  //Hole für ID die Veranstaltungen
  $veranstaltungen = $this->getVeranstaltungenByID($currentID);
  $veranstaltungen = json_decode($veranstaltungen, true);

  //Nur wenn Veranstaltungen da sind, abrufen.
  if($veranstaltungen != "NULL"){
    foreach ($veranstaltungen as $key => $value) {
    $csv = $csv.$currentID.","
    .$value['IDVERANSTALTUNG'].","
    .$value['BEZEICHNUNG'].","
    .$value['SWS'].","
    .$value['CREDITS'].","
    .$value['HAEUFIGKEIT_PA'].","
    .$value['FAKTOR_DOPPELUNG'].","
    .$value['SOMMER'].","
    .$value['WPF'].","
    .$value['KOSTEN_PA']."\n";
    }
  }
}

return $csv;

}

returns a valid csv string like that "a,b,c,d".

My Javascript looks like:

function csvExport(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200){ 
            console.log(this.responseText);
        }
    };
    xmlhttp.open("GET", "csvExport.php", true);
    xmlhttp.send();
}

In the callback, I want to download the this.responseText as a CSV file. Is that possible?

Upvotes: 0

Views: 653

Answers (1)

Milan Jaric
Milan Jaric

Reputation: 5646

Instead of console.log in ajax onreadystatechange handler call this function

function downloadAsFile(csv, fileName) {
  var file = new File([csv], fileName, { type: "text/csv" })
  var anUrl = window.URL.createObjectURL(file)
  var a = window.document.createElement('a');
  a.href = window.URL.createObjectURL(file)
  a.download = fileName;
  a.click();
}

Upvotes: 2

Related Questions