0

I'm using ajax to post array data, and on success have it download a csv file. Everything works fine except I'm getting some extra data (string) in the first column header. How do I get rid of this?

Here's my JS:

<!-- Submit Roster ------------------------------------------------------------>
<script>
$('#downloadRosterCSV').on("click", function() {
//$('.loading').show();

var email = [];
var name = [];
var id = [];
var gclass = <?php echo '"'.$courseNAME. '.csv"' ?>;

$("input:checkbox[class=ckbRoster]:checked").each(function() { 
                email.push($(this).attr("email"));
                name.push($(this).attr("name"));
            }); 


    $.ajax({
        type: "POST",
        url: "csv.php",
        data: {email: email, name: name, gclass: gclass},
        dataType: 'html',
        cache: false,
        //success: function() {window.location.assign(<?php echo '"temp/rosters/' . $courseNAME. '.csv"' ?>);$('.loading').hide();},
        //success: function() {window.location.assign("csv.php");}, 
        success: function(data){

              /*
               * Make CSV downloadable
               */
              var downloadLink = document.createElement("a");
              var fileData = ['\ufeff'+data];

              var blobObject = new Blob(fileData,{
                 type: "text/csv;charset=utf-8;"
               });

              var url = URL.createObjectURL(blobObject);
              downloadLink.href = url;
              downloadLink.download = <?php echo '"' . $courseNAME. '.csv"' ?>;

              /*
               * Actually download CSV
               */
              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);

        }
            }); 
});

</script>
<!-- END ---------------------------------------------------------------------->

And here's my PHP:

<?php
session_start();
header("Content-Type: text/csv");

$_SESSION["student_email"] = $_POST["email"];
$_SESSION["student_name"] = $_POST["name"];
$_SESSION["student_googleclass"] = $_POST["gclass"];

$email = $_SESSION["student_email"];
$name = $_SESSION["student_name"];
$gclass = $_SESSION["student_googleclass"];
  
$roster = array('Student Name' => $name, 'Student Email' => $email);

$heads = array_keys($roster);
$maxs = array();
foreach($heads as $head)
  $maxs[] = count($roster[$head]);
ob_start();
$fp = fopen('php://output', 'w');
fputcsv($fp, $heads);
for($i = 0; $i < max($maxs); $i++)
{   
    $row = array(); 
    foreach($heads as $head)
       $row[] = isset($roster[$head][$i]) ? $roster[$head][$i] : '';
    fputcsv($fp, $row);   
}
fclose($fp);
$roster = ob_get_clean();
var_dump($roster);
?>

EDIT: Here's how I ended up changing by PHP thanks to Felippe Duarte...

<?php
session_start();
header("Content-Type: text/csv");

$_SESSION["student_email"] = $_POST["email"];
$_SESSION["student_name"] = $_POST["name"];
$_SESSION["student_googleclass"] = $_POST["gclass"];

$email = $_SESSION["student_email"];
$name = $_SESSION["student_name"];
$gclass = $_SESSION["student_googleclass"];
  
$roster = array('Student Name' => $name, 'Student Email' => $email);

$heads = array_keys($roster);
$maxs = array();
foreach($heads as $head)
  $maxs[] = count($roster[$head]);
//ob_start();
$fp = fopen('php://output', 'w');
fputcsv($fp, $heads);
for($i = 0; $i < max($maxs); $i++)
{   
    $row = array(); 
    foreach($heads as $head)
       $row[] = isset($roster[$head][$i]) ? $roster[$head][$i] : '';
    fputcsv($fp, $row);   
}
ob_start();

fclose($fp);

//var_dump($roster);
echo $roster;

$roster = ob_get_clean();

?>

Here's an example of the spreadsheet results (I've hidden names and emails for privacy reasons): spreadsheet

So again, how do I just leave "Student Name" (without the quotes). Many thanks!

4
  • 4
    var_dump($roster); is probably your issue. Commented Aug 27, 2020 at 19:02
  • You could probably just remove the ob_* calls and output the csv directly. Commented Aug 27, 2020 at 19:05
  • @FelippeDuarte, thanks for the suggestion but now the csv returns nothing Commented Aug 28, 2020 at 0:14
  • @NigelRen, thanks. Could you elaborate on how to output the csv directly? I'm still a novice at this and all I could find required ob_* calls. Commented Aug 28, 2020 at 0:28

1 Answer 1

1

Replace var_dump($roster) with echo $roster;.

You already set the header as csv, as long as you format the csv (comma separated values) accordingly, the software will interpret it and display the way you want.

Sign up to request clarification or add additional context in comments.

1 Comment

That helped. Thanks!

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.