0

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);
        }
    });
});
Reece
  • 2,581
  • 10
  • 42
  • 90
  • What php version do you have on server? Have you tried to put the use / import of other classes at the top of the file? Below namespace? – Nikola Kirincic Jun 18 '19 at 11:53
  • What error are you getting? Are you calling the function? – blues Jun 18 '19 at 11:55
  • @blues Oh that error doesn't matter now. It was because I was was declaring use inside my function. I now know that it must be declared in the outermost scope of the file – Reece Jun 18 '19 at 12:02
  • @niklaz I'm running php 7. I have no idea what your asking in your second question sorry – Reece Jun 18 '19 at 12:04

1 Answers1

1

Modify Your Code as :

require_once 'vendor/autoload.php';

function email_campaign(){
    $path = dirname(__DIR__).'/sheets';
    $fileName = 'hello_world.xlsx';

    $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', 'Hello World !');
    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save($path.'/'.$fileName);
}
Imran Khan
  • 311
  • 4
  • 9