In public/js file, I request $ajax, and get responding just string, not file.
If the client sends a request using ajax, the server responds with a string instead of xlsx file.
Here is request part:
$("#downloadXLS").on('click', function () {
$.ajax({
type: 'get',
url: appRoot "transactions/downloadXLS/",
success: function () {
},
error: function () {
}
});
});
And here is php responding function:
public function downloadXLS()
{
// Filter the excel data
function filterData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// Excel file name for download
$fileName = "transaction-data_" . date('Y-m-d') . ".xls";
// Column names
$fields = array('No.', 'Pay Date', 'Company');
// Display column names as first row
$excelData = implode("\t", array_values($fields)) . "\n";
// Headers for download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$fileName\"");
$allTranscations = $this->transaction->getAll();
if (is_array($allTranscations)) {
// Output each row of the data
foreach ($allTranscations as $key => &$trans) {
$lineData = array($key 1, $trans->pay_time, $trans->company);
array_walk($lineData, 'filterData');
$excelData .= implode("\t", array_values($lineData)) . "\n";
}
} else {
$excelData .= 'No records found...' . "\n";
}
// Render excel data
echo $excelData;
exit();
}
CodePudding user response:
You can't download file via ajax request. Try location.href=transactions/downloadXLS.