Set JavaScript variable from PHP

How I can set the JavaScript variable strUser from PHP?

I am using the following code:

<script>
function val()
{
    var e = document.getElementById("ali");
    var strUser = e.options[e.selectedIndex].text;

}
</script>
brand<select id="ali" onChange="val()">
<?php
   $brand=modsearchkhodroHelper::retrieve();
   foreach($brand as $item)
   {   
   ?>
       <option value="<?php echo $item['brand']?>" selected="<?php  $id=$item['brand']?>">
           <?php echo $item['brand']?>
       </option>
   <?php
   }
   echo "</select>";
?>

Answers:

Answer

If you want to set the variable when the page loads, you could use something like this in the PHP code:

<script type="text/javascript">var strUser = <?php echo json_encode($someVariable); ?>;</script>

Just make sure to remove the later variable declaration from the JavaScript.

If you want to set the variable after the page loads, you'll have to use an AJAX call to ge the value from the server.

Answer

Use Cookie in your javascript

<script type="text/javascript">
    document.cookie = "cookieName=cookieValue";
</script>

in your php

<?php 
   $phpVar =  $_COOKIE['cookieName'];

   echo $phpVar;
?>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.