I have the following scenario:
A Wordpress plugin (shortcode) is showing a form with a "submit" button. When the submit button is pressed, an Excel 2007 file (.xlsx) is generated and sent to the browser for download via HTTP headers. This works perfectly in Chrome and Firefox, but when I try this using the Microsoft Edge browser (v. 40.15063.0.0) or Internet Explorer (v. 11.540), the download is not triggered, instead the browser redirects directly to
http://example.com/wp-admin/admin-ajax.php
and stops.
I suspect it has something to do with the headers sent by the plugin (php). When I changed the content-type header from
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
to
Content-Type: application/vnd.ms-excel
it starts a file download, however the file is empty (and had the wrong file name) because the File I generate is Excel 2007 but the latter content type is for an older Excel file version (which I do not want to generate). I also tried both content types with added ;charset=utf-8 with the same result.
Excerpt from my main plugin file:
add_action( 'wp_ajax_myplugin_generate_report', 'handle_report_request' );
add_action( 'wp_ajax_nopriv_myplugin_generate_report', 'handle_report_request' );
function handle_report_request() {
// Check the nonce
if ( empty($_POST) || !wp_verify_nonce($_POST['abcd'],'myplugin_generate_report') ) {
exit;
}
try {
$date = new DateTime("now");
$output_filename = "Report_Prefix" . $date->format("Ymd");
$writeExcel($output_filename);
} catch (Exception $ex) {
echo "Error generating report: " . $ex->getMessage();
} finally {
wp_die();
}
}
function writeExcel($outputFilename) {
$excelObj = new PHPExcel();
[... populating PHPExcel object ...]
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', true, 200);
header('Content-Disposition: attachment;filename="' . $outputFilename . '.xlsx"');
// header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header('Cache-Control: max-age=0');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($excelObj, 'Excel2007');
$objWriter->save('php://output');
}
The HTML/PHP code with the form elements:
<form action="<?php echo admin_url('admin-ajax.php'); ?>" method="post">
<?php wp_nonce_field('myplugin_generate_report','abcd'); ?>
<input name="action" value="myplugin_generate_report" type="hidden">
<input type="submit" value="Generate report">
</form>
I have tried deactivating/changing some headers but to no effect. Edge refuses to generate the file.