Pass PHP variable in Javascript

Asked

Viewed 874 times

0

I want to pass a variable that is in php, for 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 doesn’t work.

  • Do you think this answer was correct for your question? If yes you can mark as certain.

1 answer

3

I see three problems:

#1 you want a string

Then it’ll have to have quotes:

var color = "codigo_da_côr";
            ^             ^

#2 missing a dot and comma: ;

Missing one ; after the PHP variable, must be:

<?php $color; ?>
            ^

#3 missing an echo

As Jader noted well, the variable has yet to echo...

Can do <?=$color;?> if you don’t want to use echo (shortcut), or you must have echo thus <?php echo $color; ?>

Correct code:

var color = "<?php echo $color; ?>";
  • Still missing an echo

  • @Jader true! I joined, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.