Skip to content
Advertisement

PHPExcel download using ajax call

App::import('Vendor', 'PHPExcel/Classes/PHPExcel');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('ReceivedMessages');
header('Content-Type: application/vnd.ms-excel');
$file_name = "kpi_form_".date("Y-m-d_H:i:s").".xls";
header("Content-Disposition: attachment; filename=$file_name");
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

When I call above code directly from the browser, the result file is downloaded. But if I make an ajax call to above code, I don’t get the download prompt. I can see from console tab that the ajax call was successfully completed and a bunch of random characters is seen in the response data. I’m assuming that is the excel object.

Does anyone know how I can achieve the download excel feature using ajax? I don’t want to refresh the page. When the user clicks on the “export” button, there should be an ajax call to the php file and prompt the user to download.

Advertisement

Answer

add target=_blank in your ajax success function like below

success: function(){
  window.open('http://YOUR_URL','_blank' );
},

otherwise you can handle smartly to open your Excel download link in new tab with jQuery trigger function or etc.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement