javascriptphpjqueryhtmlcsv

jQuery download a csv file with link onclick


I'm trying to download a CSV file using jquery button onclick. I have an <a> tag with id export where I want it to point to the download link where I can download the CSV file that I just created.

// Using this jquery to send my sql query to server-side-CSV
$('#export').on('click', function() {
  var sqlsend = dataTable.ajax.json().sql;
  $.post('server-side-CSV.php', 'val=' + sqlsend, function(request){
    //code should go here
  });
});

And here's my php code where I'm creating a CSV file

// This is my server-side-CSV file. It's creating a csv file to     downloaded
<?php
require("connection.php");
$sql = $_POST['val'];
.
.more code
.

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
fclose($output);
exit;
?>

What can I do to download the CSV file?

EDIT: Finally figure out the answer,

$('#export').on('click', function() {
  var sqlsend = dataTable.ajax.json().sql;
  window.location.href="server-side-CSV.php?val="+sqlsend;
});

Solution

  • Instead of $.post, send the browser to download location:

    document.location.href = 'server-side-CSV.php?val='+sqlsend;
    

    You need to add headers before the loop.

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    

    See this answer.