Allkill Allkill - 1 year ago 93
HTML Question

jQuery download a csv file with link onclick

I'm trying to download a CSV file using jquery button onclick. I have an

tag with id
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
$sql = $_POST['val'];
.more code

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

What can I do to download the CSV file?

Finally figure out the answer,

$('#export').on('click', function() {
var sqlsend = dataTable.ajax.json().sql;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download