0

In PHP I am generating an array with all files I have stored in one repository on the server. I need a list of those files in my javascript.

I saved the PHP array to an .json file.

$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data); 

This file I access via fetch from my javascript.

Now my question. Is this a pracical way to go? I feels like a long stretch to generate an extra .json file simply to get the names of all files stored in one folder. Is there any other way to read the array directly from php?

My PHP File

<?php
$dir = "uploads";    
$allCakesPHP = scandir($dir);
$allCakesJSON = json_encode ($allCakesPHP);
header("Location:index.html");
?>
/* file_put_contents("allCakesJSON.json", $allCakesJSON); */
<script type="text/javascript">var jsonData = <?php echo json_encode($allCakesJSON);?> ;</script>
<script type="text/javascript" src="visuTorte.js"></script>

My how i tried to acces the array in javascript

var test = jsonData;
  • 1
    Sure, just `echo $json_data;`, instead of writing it to a file ...? – CBroe Oct 18 '21 at 08:40
  • You don't need to put the json in a file and fetch it ... just in javascript do : var jsonData = '' ; this will put your json in the var jsonData... – Shlomtzion Oct 18 '21 at 10:42
  • Does this also work with an external js file? I tried the recomondation here but couldn't get it to work. https://stackoverflow.com/questions/2928827/access-php-var-from-external-javascript-file. I included the some code to my question. – Tobias Gerling Oct 18 '21 at 19:20

0 Answers0