Skip to content
Advertisement

Download a file with an ajax call

I am using PHPExcel to read an excel template, populate the data, and ask the user to download the file.

generate_excel.php

$objPHPExcel = PHPExcel_IOFactory::load("./template.xlsx");
//populate data ...
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

When I open generate_excel.php directly from the browser, the result file is downloaded. But if I make an ajax call to the generate_excel.php, I don’t get the download prompt. Using chrome developer tools, I can see from the Network 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.

Thanks!

Advertisement

Answer

Found a way to do this, although I’m not sure if this is an ideal approach.

I added a hidden iframe in the page. When the ajax call returns, it returns the url of the created data. I used javascript to redirect the iframe to that url which automatically triggers the download action.

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