Reputation: 2459
I have looked through a few similar questions but can't quite find what I am looking for (please don't mark this as duplicate as I did try to find an answer without posting a question)
When the user clicks on a button, an ajax request is sent to the controller where I am getting data back from the model. I am then converting it to a csv format and on success of the ajax call I want the file to download. I have everything working except the download part. I have seen some examples where you just redirect but that doesn't download anything, it shows a new page with the results.
$( '.spExcel' ).on('click', function() {
$.ajax({
url: url + '/Widgets/exportSpExcel',
type: 'POST',
})
.done(function (data) {
window.location.assign(data);
})
});
PHP:
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$results = $this->DashboardModel->listPeople();
$filename = 'People_' . date('dmY') . '.csv';
header("Content-Description: File Transfer");
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$handle = fopen('php://output', 'w');
$header = array("Name", "Contact Number");
fputcsv($handle, $header);
foreach ($results as $result):
fputcsv($handle, $result);
endforeach;
fclose($handle);
}
Upvotes: 0
Views: 65
Reputation: 26143
Ajax isn't capable of writing a downloaded file - the browser has to do that itself. You could use window.open()
but that would open the file in a new tab or window, which would then close immediately. That can look messy - it works but isn't ideal.
The simplest way to deal with this is to make the link download the response directly, without trying to use Ajax. Change the link to suit your needs, but it would be something like this...
<a href="/Widgets/exportSpExcel" class="spExcel" download>click to download</a>
Just add the download
attribute to a link. It really is that simple :)
Upvotes: 1