I'm writing PHP code (in drupal) to export data to excel file using ajax i'm not receiving any error but file is not getting download when I click button to export to excel. But file getting download when i directly heat the url(from browser)
This is the ajax code
jQuery('.export-csv', context).once('export').click(function() {
console.log('test');
var role = 'teacher';
/*get basepath*/
var basepath = drupalSettings.path.baseUrl;
jQuery.ajax({
type : 'GET',
url : basepath + 'report-export/'+role,
success : function (data) {
console.log('success');
},
error: function () {
console.log('error');
}
})
})
and php function in controller to download excel file
public function exportToExcel($role)
{
$filename = "report.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
$records = array(
'0' => array('Name'=> 'user1', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'user2', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'user3', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'user4', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'user5', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'user6', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "
";
$heading = true;
}
echo implode("\t", array_values($row)) . "
";
}
exit;
}
though i m not getting error but file not getting downloading. and in ajax console also getting success message. and when i direct hit url as
site.com/report-export/
file gets download