Got an array from the database. Need to handle it in javascript. Help)

<?php $id1 = array("id" => "1", "name" => "block"); $json = json_encode($id1); ?> <script> var id1 = JSON.parse(<?php echo $json; ?>); </script> //Что я делаю не так в использовании JSON формата? 
  • In the js code itself, you can use the php method: json_encode . Example: var id1 = <?php echo json_encode($json) ?>; - x_ror
  • and what errors in the console javaskript sypyatsya? - rjhdby

2 answers 2

Alternatively, try wrapping the output in quotes;

 <script> var id1 = JSON.parse('<?php echo $json; ?>'); </script> 
  • Give an example of the output <? Php echo $ json; ?> - Roman Polshikov
  • @AlexChebotarsky Look in the browser the source code of the resulting page. - Mike
  • Sorry, I asked you a question for a long time, and only now I unsubscribe. I went to the console (by the way, I didn’t know that the console is so convenient tool for warning about errors in js, thanks, now I know), and I saw that an array was inserted into js, ​​of course in json format, but it was without quotes, added everything was fixed and ran joyful to continue module, and did not thank their saviors, thanks to everyone! - Alex Chebotarsky

and as an option this is just pure with arrays

  var id1 = <?php print_r($arr); ?>; 
  • For your example, you do not need to build working code. It is enough to use the “Sample Code” button (with curly quotes) or just indent by 4 spaces. - Gleb Kemarsky