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 ?