3

I want to generate a .csv file then download it with AJAX

Insite csv.php I have this code:

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


$file = fopen("th.csv","r");
$list = array();

while(! feof($file))
  {
      $list[] = (fgetcsv($file));
  }
fclose($file);

$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

$list = array_filter($list);
outputCSV($list);

function outputCSV($list) {
    $output = fopen("php://output", "w");

    foreach ($list as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
?>

so when I'm going to csv.php it makes me download the csv file.

Then inside test.php I have this jQuery code:

$(document).on('click', '#listCSV', function() {

        var el = $(this),
            csv = el.attr('csv');
        $.ajax({
            type: 'POST', 
            url: 'csv.php',
            data: {
                listCSV: csv
            },
            success: function(data, textStatus, jqXHR) {
                el.html($(data));
            }
        });
    }); 

But when I'm clicking on #listCSV nothing happens, nothing is being downloaded

Any idea how can I download the csv file when clicking on #listCSV?

user2461031
  • 513
  • 2
  • 7
  • 17
  • maybe this links would point you to the right direction. [answer1](http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax), [answer2](http://stackoverflow.com/questions/6668776/download-file-through-an-ajax-call-php) – user1978142 May 08 '14 at 03:53

2 Answers2

0
  1. generate the csv file and store it in a directory. say: root/csv/file_timestamp.csv
  2. when the file is generated just use the file_timestamp.csv location on you're link. so if your file_timestamp.csv is can be accessed via

    http://project/csv/file_timestamp.csv

then just link it to a regular link:

<a href="http://project/csv/file_timestamp.csv"/>download csv</a>

Note: if you're not expecting multiple users to generate csv files then just make a temporary file then you can set the link as static. if not just delete every file in the csv folder every 3mins

Viscocent
  • 2,024
  • 2
  • 19
  • 26
0

You need to change header information to output it as download :

        $out = fopen("php://output", 'w');
        $emails = array();
        header('Content-Type: application/download');
        header('Content-Disposition: attachment; filename="'.$this->filename.'.csv"');
        foreach($contacts as $adr) $emails[] = $adr->getEmail();
        fputcsv($out, $emails);
        fclose($out);
        exit;
DarkBee
  • 16,592
  • 6
  • 46
  • 58