Basically, I am coding in Wordpress, created a function that just shows Hello World and download automatically on the browser but doesnt seem to work?
Inside: Functions.php
wp_enqueue_script('llc-quote-profile-autocomplete', get_template_directory_uri() . '/llc-quote-profile-autocomplete.js', array('jquery', 'jquery-ui-autocomplete'), null, true);
wp_localize_script('llc-quote-profile-autocomplete', 'llcQuoteAutocomplete', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('llc_quote_profile_autocomplete_nonce'),
));
require_once(ABSPATH . 'vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
function export_data_to_excel() {
$spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
$activeWorksheet = $spreadsheet->getActiveSheet();
$activeWorksheet->setCellValue('A1', 'Hello World !');
$writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="hello_world.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
}
add_action('wp_ajax_export_data_to_excel', 'export_data_to_excel');
add_action('wp_ajax_nopriv_export_data_to_excel', 'export_data_to_excel');
Inside Custom Javascript.js
$('#llc-quote-details').on('click', '#exportExcelAndPDF', function() {
var customersPo = $('#edited-customers-po').val();
$.ajax({
url: llcQuoteAutocomplete.ajaxurl,
type: 'POST',
data: {
action: 'export_data_to_excel',
customers_po: customersPo,
nonce: llcQuoteAutocomplete.nonce,
},
success: function(response) {
},
error: function(xhr, status, error) {
console.error(error); // Log any AJAX errors for debugging
}
});
});
I am only testing first via Hello World because if this works, I can export any data now.
Well.
- Setting up the headers to allow it
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="hello_world.xlsx"');
header('Cache-Control: max-age=0');
- Tried Google Chrome, MS Edge, Mozilla Firefox but still cannot download.
This is a security feature of the Chrome engine and the Firefox Engine. You can use jQuery to click the link if the file is ready for the auto download.