1

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;
});
Amitoz Deol
  • 65
  • 1
  • 9

1 Answers1

0

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.

Community
  • 1
  • 1
olegsv
  • 1,422
  • 1
  • 14
  • 21
  • Yes I already have all these headers. Stackoverflow didn't let me add all the code. – Amitoz Deol Nov 14 '16 at 15:04
  • I recommend to check whether your server-side-CSV.php file works with some SQL hardcoded into it. Call it directly from browser. – olegsv Nov 14 '16 at 15:10
  • Yes it's working perfectly fine when I pass my own SQL query. When I'm passing the sql query, function(request), this 'request' variable contains all the data but not showing any download popup. – Amitoz Deol Nov 14 '16 at 15:16
  • Edited my answer. – olegsv Nov 14 '16 at 17:01