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_I
Not everything should be done with AJAX. Sometimes plain old HTML is more suitable for a job. I guess your button has a
tag? Why won't you do something like this
<a href="generate_excel.php" target="_blank">Export to Excel</a>
in your HTML? Note the target="_blank"
part. It's there to make sure your page is not reloaded.
For input
you can use construct
<form action="generate_excel.php" target="_blank"><input type="button">...whatever</form>
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.
I don't think you can download anything by ajax call. Instead of you can generate and save the excel in server (temporary) and show the download link to the user.
I looked for ways to pass JSON data with ajax to PHP and return an excel file (MySQL and PHPExcel) for the user to save. I looked around and put some pieces together, hope it can help someone:
jQuery:
$("#exportBotton").on("click",function(event) {
event.preventDefault();
// create json object;
str_json = JSON.stringify({"key01":val01, "key02":val02, "key03":val03});
$.ajax({
type: "post",
data: str_json,
url: "../../includes/dbSelect_agentFormExport.php",
dataType: "json",
success: function(output){
// output returned value from PHP t
document.location.href =(output.url);
}
});
});
PHP:
$str_json = file_get_contents('php://input');
$objPHPExcel = new PHPExcel();
// here i populated objPHPExcel with mysql query result.....
function saveExcelToLocalFile($objWriter){
// make sure you have permission to write to directory
$filePath = '../tmp/saved_File.xlsx';
$objWriter->save($filePath);
return $filePath;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = array(
'success' => true,
'url' => saveExcelToLocalFile($objWriter)
);
echo json_encode($response);
exit();
You can try this way: