Using PHP in a <script> tag?

I am trying to create an object in javascript with PHP. This is my script:

<script> $(document).ready(function(){ var genres = [ <?php $last = count($userGenres) - 1; $i = 0; foreach($userGenres as $a){ $i++; echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}'; if($i < $last){ echo ','; } } ?> ]; }); </script> 

When I check the generated source, it creates a valid object, but the whole script in this tag does not work. How to fix it without JSON?

thanks

+6
source share
4 answers

As the comment says, you should instead use the (php function) json_encode function, which will ...

 php: $a = array( array("gender"=> "male", "name"=> "Bob"), array("gender"=> "female", "name"=> "Annie") ); Into json: [ {gender:"male", name:"Bob"}, {gender:"female", name:"Annie"} ] 

Echoing json_encode ($ a) prints it in exactly the same way.

0
source

You forgot to close the .ready() method and the anonymous function inside it.

Try the following:

 <script> $(document).ready(function(){ var genres = [ <?php $last = count($userGenres) - 1; $i = 0; foreach($userGenres as $a) { $i++; echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}'; if($i < $last) { echo ','; } } ?> ]; }); </script> 
+1
source

Your function is not closed properly:

 } } ?> ]; }); // <--- add this </script> 
0
source

It:

 <script> $(document).ready(function(){ var genres = [ <?php $last = count($userGenres) - 1; $i = 0; foreach($userGenres as $a) { echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}'; if($i < $last) { echo ','; } $i++; } ?> ]; }); </script> 

Changes: You need to close the anonymous function and the ready () method. Also, move i ++ to the end so that you cover all cases (you are missing one). Error due to i ++ error.

0
source

Source: https://habr.com/ru/post/902638/


All Articles