user2627035
user2627035

Reputation: 85

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>";
?>

Upvotes: 6

Views: 37987

Answers (2)

Padmanathan J
Padmanathan J

Reputation: 4620

Use Cookie in your javascript

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

in your php

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

   echo $phpVar;
?>

Upvotes: 5

Joshua Dwire
Joshua Dwire

Reputation: 5443

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.

Upvotes: 19

Related Questions