0

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?

0

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! the parameter csv can be any arbitrary string. (Hopefully valid CSV syntax in this particular case)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.