0

What I want to do: 1,use Javascript ajax POST array to PHP; 2,use POST array to search result from mysql with PHP; 3,return search results with csv format, so user can save the file. I have accomplished part 1 and part 2, but I can't get csv file returned I use ajax to POST array data to PHP like this:

$(document).ready(function(){
$('#export').click(function(){
    var list = JSON.stringify(count);
    $.ajax({
        type: "POST",
        url: "exportDataColoniesNumber.php",
        data: {'data': list},
        success: function(response){
            alert(response);
        }
    });
});
});

And process the data in exportDataColoniesNumber.php, and the page is to return a csv file:

<?php
$data = json_decode($_POST['data']);
$last_key = end(array_keys($data));
$sql = "SELECT * FROM coloniesNumber WHERE ";
foreach ($data as $key => $value) {
    $sql .= "num='" . $value . ($key == $last_key ? "';" : "' OR ");
}

$con = DatabaseConnection::get()->connect();
mysql_query('set names utf8');
mysql_select_db('fish') or die('Could not select database');
$result = mysql_query($sql);

$lines = '';
while($row = mysql_fetch_array($result)) {
    $line = '';
    for($i = 0; $i < $fields; $i++) {
        $line .= $row[$i] . ",";
    }
    $lines .= trim($line) . "\n";
}
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:csv".date("Y-m-d").".csv");
header("Content-disposition:filename=test.csv");
print "$lines";
?>

The alert(response) return csv data:

8,4008,11.267,fat,1,,
9,4009,12.022,thin,1,,
10,4010,11.356,thin,1,,
11,4011,10.873,thin,1,,
12,4012,11.017,thin,1,,
13,4013,11.301,thin,1,,

How can I get csv file returned ?

rawk
  • 1
  • 1
  • 1

1 Answers1

1

Personally i've created a PHP handler that exports to csv, make sure you have these headers

header("Content-Disposition: attachment; filename=report.csv");
header("Content-Type: text/csv");

Then just echo your data, csv-formatted or use one of the many free csv classes that does that for you (just call a function with an Array as a parameter)

Then make your form (asuming you have one) post to a hidden iframe of 1x1 pixels and set offscreen with css

iframe { position: absolute; left: -9999px; }

You should be all set, and the export will pop up - however, make sure the file is not big or your script takes a lot of time to complete - until then, the download won't show up.

ied3vil
  • 964
  • 1
  • 7
  • 18