Home » Php » How to pass a value from PHP to JS?

How to pass a value from PHP to JS?

Posted by: admin June 30, 2018 Leave a comment

Questions:

I have a PHP code that creates a spreadsheet file (.xlsx) in the server, using the PhpSpreadsheet library, like so:

<?php

//Including the library
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

//Creating the file

$file = 'excel/myfile.xlsx'; //File path and name
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World!');
$writer = new Xlsx($spreadsheet);
$writer->save($file); //Saving the file

?>

This code can/cannot be executed more than once, meaning it can create multiple spreadsheet files inside the same directory. For demonstrating purposes it’s just creating all files with the same name but, obviously, in the final project each file will be given a diferent name (e.g. “myfile1.xlsx”, “myfile2.xlsx”, etc…).

Later on, in the same page, I want to have a JS code that “fetches” the file’s path/name (stored in $file) and downloads the file. This code is only executed when the PHP code is executed.

Think of this as a button (or more, in a row) that, when clicked, magically executes the PHP code – creating the file – and then the JS code – downloading the file.

Can somebody help? How do I fetch the file’s path/name and how do I download it after? Thanks in advance!

Answers: