Home > front end >  php var inside javascript inside php
php var inside javascript inside php

Time:02-17

so I've tried a few things but nothing seems to work. what im trying to do is

<?php
  $php_var = a-thing;
  echo '
  <script text/JavaScript>
    document.cookie = "arrayid" '.$php_var.' ;
  </script>
';
?>

so when im not trying to set the array placement '.$php_var.' through just fine. can someone please help me with what I would assume is a syntax error on my part, please

CodePudding user response:

Three things:

  1. (php) You have an erroneous semi-colon ; after $php_var
  2. (js) You need double quotes around the javascript string (if $php_var is a string)
  3. (html) You are missing the type= attribute name in the script tag (you are using the default value for the attribute so you could just use <script>...</script> instead)
<?php
  $php_var = a-thing;
  echo '
  <script type="text/JavaScript">
    document.cookie = "arrayid" "'.$php_var.'";
  </script>
';
?>

CodePudding user response:

You can try this: <?=$php_var;?> this will echo the variable in normal html code.

<?php
  $php_var = "a-thing";
?>
  <script text/JavaScript>
    document.cookie = "arrayid" <?=$php_var;?>;
  </script>

CodePudding user response:

Try this:

<?php
$aThing=7;
$php_var = $aThing;
echo '<script>document.cookie ="arrayid'.$php_var.'";</script>';?>

There is not much to explain. The PHP script generates the following string:

<script>document.cookie ="arrayid7";</script>

I left out the text/JavaScript part, as HTML5 does not require this anymore.

See the little demo here: https://rextester.com/HSCMD53489

  • Related