Quantcast
Viewing all articles
Browse latest Browse all 82155

How to download csv using ajax request

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
{
    "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" );
                }
            } );
    }
}

My php file
<?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']);
?>


Please help me. Thanks.

Viewing all articles
Browse latest Browse all 82155

Trending Articles