I have created a AJAX function that runs on a click event on the front end. Inside this function I want to be able to generate a XLS Spreadsheet but I am unable to do this inside the function. I believe its to do with me declaring the use statements outside the function maybe the function is unable to access the classes? I tried declairing them inside the function and I got this error;
syntax error, unexpected 'use'
Doe's anyone have a solution for this? Here's my code;
add_action('wp_ajax_nopriv_campaign', 'email_campaign');
add_action('wp_ajax_campaign', 'email_campaign');
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
function email_campaign(){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
die();
}
here is how I call my function;
$('#campaign_form').submit(function(e){
e.preventDefault();
$.ajax({
url: ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'campaign'
},
error : function(response){
console.log(response);
},
success : function(response){
console.log(response);
}
});
});