Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP in <script> tag?

I'm 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 that tag doesn't work now. How would fix this, without JSON?

Thanks

like image 597
Gregor Menih Avatar asked Nov 29 '11 11:11

Gregor Menih


People also ask

Can we use PHP in script tag?

It's just a regular HTML <script> tag that calls a PHP file instead of a JavaScript file. But there's one catch: In that PHP file, you still have to use JavaScript.

Can you use JavaScript and PHP together?

Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.

How do I tag PHP in HTML?

PHP syntax is applicable only within PHP tags. PHP can be embedded in HTML and placed anywhere in the document. When PHP is embedded in HTML documents and PHP parses this document it interpreted the section enclosed with an opening tag (<? php) and closing tag (?>) of PHP and ignore the rest parts of the document.


2 Answers

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

Try this:

<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>
like image 110
Kemal Fadillah Avatar answered Oct 15 '22 13:10

Kemal Fadillah


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

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) would output it just like that.

like image 31
Lars C. Magnusson Avatar answered Oct 15 '22 11:10

Lars C. Magnusson