How to download csv using ajax request

How to download csv using ajax request

pinquanpinquan Posts: 2Questions: 0Answers: 0
edited April 2013 in TableTools
Hello,

I've been solving this issue for a whole 2 days now.
I'm trying to pass json from the datatable to a php file for processing and a csv will be downloaded.
I received the success message "Ajax complete". But no csv file being downloaded.

My ajax button code
[code]
{
"sExtends": "ajax",
"bHeader" : false,
"sFieldSeperator": ",",
"sAjaxUrl" : "AttendanceList.php",
"fnClick": function( nButton, oConfig ) {
var sData = this.fnGetTableData(oConfig); //B,A,123,4,B
$.ajax( {
"url": oConfig.sAjaxUrl,
"data": [
{
"name": "tableData",
"value": sData
}
],
"success": oConfig.fnAjaxComplete,
"dataType": "html",
"type": "POST",
"cache": false,
"error": function () {
alert( "Error detected when sending table data to server" );
}
} );
}
}
[/code]

My php file
[code]
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=AttendanceList.csv');

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

function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals); // add parameters if you want
}

array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}

outputCSV($_POST['tableData']);
?>
[/code]


Please help me. Thanks.

Replies

  • allanallan Posts: 63,679Questions: 1Answers: 10,498 Site admin
    Please read the forum rules and link to a test case: http://datatables.net/forums/discussion/12899/post-test-cases-when-asking-for-help-please-read

    Having said that, you might want to use the download plug-in on this page, rather than an Ajax request: http://datatables.net/extras/tabletools/plug-ins

    Allan
This discussion has been closed.