I am struggling with achieving what I want and am not sure if it is possible. I am using CodeIgniter
and PHP
for my web application. My home view allows users to query a database and the results are generated and displayed in the table form on the page. The user will then review the table and be provided the option of downloading as an xlsx
Excel file. I am using an ajax post to send the table data to my PHP controller
that will create the Excel file. I also need this to work in all browsers especially Safari, as the client will access the application from Ipads as well as desktop machines.
My home ajax post: (t is the id of the generated table)
$("#btnExport").click(function() {
$.ajax({
type: "POST",
url: '<?php echo base_url();?>index.php/Home/excel',
datatype: 'html',
data: {
'queryData': $("#t").html()},
success: function (response) {
alert(response);
}
});
});
My controller function:
public function excel()
{
$this->load->library('excel');
$filename = "data";
$table = $this->input->post('queryData');
$objPHPExcel = new PHPExcel();
$tmpfile = time().'.html';
file_put_contents($tmpfile,$table);
$objReader = PHPExcel_IOFactory::createReader('HTML');
$objPHPExcel = $objReader->load($tmpfile);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename='.$filename);
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
unlink($tmpfile);
}
The problem is the handling of the ajax response I've read its impossible to download a file from ajax. Everything I have tried is not working The response is binary encoded data I am assuming is the excel file. Is there a workaround to this problem? I decided on ajax as the table can change dynamically given the current query, and needs to be sent to the server accordingly.Thanks for any assistance.
EDIT
In the linked question it is about submitting forms and not triggering a download. I am not submitting any forms, just passing an html table to the PHP
to build the Excel file. I fail to see how that is relevant to my problem. Am I misunderstanding?