1

I write the following script that creates a nice JSON of all the images under the current folder:

<?php
header('Content-type: application/json');

$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions

$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
  $files = glob(''.$dirname.'/*');
  $images = preg_grep($pattern, $files);
  
  $output->{$dirname} = $images;
}

echo json_encode($output, JSON_PRETTY_PRINT);
?>

I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.

So the question is how can I get the PHP data into a javascript variable?

<html>
    ...
    <body>
        <script src="images.php"></script>
        <script type="text/javascript">
            // Desired: Get access to JSON $output
        </script>

        ...

        <div>
          <img ... >
        </div>

    </body>
</html>

I tried to put both https://stackoverflow.com/a/61212271/1692261 and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)

user1692261
  • 1,197
  • 3
  • 16
  • 30
  • Why you don't want to make a ajax call to your PHP script and get the json? – Zeusarm Feb 18 '21 at 10:25
  • @Zeusarm Well... First time using PHP, don't know nothing about ajax. Is that the only way to make it work? If so I'll read about that too. Classic Yak shaving :) – user1692261 Feb 18 '21 at 10:45
  • If you want to 'assign' php output in the javascript variable you have to deal with quotes, etc. And if you load it client side by javascript ajax request and getting a json from php then you are getting pure javascript object which you can easily use. – Zeusarm Feb 18 '21 at 10:52
  • @Zeusarm OK cool I will have it a go. – user1692261 Feb 18 '21 at 11:20
  • @Zeusarm Works like a charm! see my answer below. Thanks! – user1692261 Feb 18 '21 at 11:29

2 Answers2

0

you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way? passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is

// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
   var images = "<?= $images ?>";
</script>

I won't guarantee that this js line is going to work but you get the idea)

P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is

  • It doesn't work. I tried a `console.log(images)` but it just print `= $images ?>`. In any case your prefix was totally right. See the answer I post to this question. Thanks! – user1692261 Feb 18 '21 at 11:31
0

I took @Zeusarm advice and just used ajax (and jquery) instead.

For others need a reference:

  1. Nothing to change in PHP script in the original post.
  2. Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  3. Make a GET request like this:
        <script type="text/javascript">
          var images = ''
          $.get('images.php',function (jsondata) {
            images = jsondata
          });

I am sure this is not the cleanest code but it works :)

user1692261
  • 1,197
  • 3
  • 16
  • 30
  • it is better to move the ajax call into script to `$(document).ready(function () { ... })` function body. It will execute the code after the HTML is loaded, and you will not have any trouble if some elements are initialized after the script tag. – Zeusarm Feb 18 '21 at 11:40
  • Got you. Done :) – user1692261 Feb 18 '21 at 11:46