Pass variable PHP into JavaScript [duplicate]

0

I want to pass a variable that is in php to JavaScript. For example this:

<?php
    $color = "Red";
?>
            <script type="text/javascript">
                var color = <?php $color ?>;

                alert("color: " + color);
            </script>

I tried this code, but it does not work.

    
asked by anonymous 25.10.2014 / 16:09

1 answer

3

I see three problems:

# 1 you want a string

Then there will have to be quotes:

var color = "codigo_da_côr";
            ^             ^

# 2 is missing a semicolon: ;

A ; is missing after the PHP variable, it should be:

<?php $color; ?>
            ^

# 3 is missing an echo

As Jader noted correctly, it is still necessary to echo the variable ...

You can <?=$color;?> if you do not want to use echo (shortcut), or you must have echo so <?php echo $color; ?>

Correct code:

var color = "<?php echo $color; ?>";
    
25.10.2014 / 16:12