Passing PHP aray into JS

I have php file that has form myfile1.php

This form will send data with GET to myfile2.php which has function that returns variable $myArray.

`myfile2.php`  contains javascript file `myscript.js` 

How do I pass $myArray to myscript.js?

Thanks

Would json_encode serve your purpose?

<script>
...some scripting...
<?php echo json_encode($myArray) ?>
... more script...
</script>
1 Like

Well I was aware of that but kept receiving error which I couldn’t de-bug so I was hoping there would be another simpler way. When I tried to use function you mentioned above I could not get any output in my console…

$(document).ready(function() {
   console.log("Just before json");
      $.getJSON('path to my php file', function(data) {
          `console.log("Inside doing something");`
        $(data).each(function(key, value) {
          //do something
        });
     });;

})

I could never get any output of this code console.log("Inside doing something");

Then I found that I need to send headers like this…

header('Content-Type: application/json');

Which I did but then got error showing in the browser like this…

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

So that got me thingking maybe my JSON is incorrecto somehow so I went back to my php file and echoed it and grabbed that output and validated it here Validator JSON and it passed so right now I am at loss.

Should that console.log() line have backticks around it?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.