1

Is there a similar way to implement this kind of "algorithm" in the right way?

for(i=0;i<howManyCourses;i++){

            var stored = "<?php echo $buf[i] ?>";
            var option = document.createElement("option");
            option.text=stored;
            e.add(option);

        }

So I want to pass the data from the $buf array into a javascript variable. I've tried many ways but it seems like I cannot find the solution. I'm new into php and I apologise for any obvious mistake.

Cand3
  • 11
  • 2
  • 3
    Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – ficuscr Jun 07 '19 at 18:49
  • 1
    Above answer and JSON. see: [json_encode](https://www.php.net/manual/en/function.json-encode.php). – ficuscr Jun 07 '19 at 18:51

2 Answers2

1

It should be in the same file or in another case AJAX will be the solution.

<script type="text/javascript">

       const arr = <?php echo json_encode($buf); ?>;

       for (var i = 0; i < arr.length ; i++) {
           //do something
       }

 </script>
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
0

If you need that JS' variable buf contain the same elements as PHP's $buf, you can do the following:

var buf = <?php echo json_encode($buf); ?>;

Just keep in mind that if PHP's $buf is not an indexed array, JS' buf will be an object instead of an array.

Eduardo Escobar
  • 3,301
  • 2
  • 18
  • 15