Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set JavaScript variable from PHP

Tags:

javascript

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>";
?>
like image 903
user2627035 Avatar asked Aug 12 '13 14:08

user2627035


1 Answers

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.

like image 171
Joshua Dwire Avatar answered Nov 07 '22 06:11

Joshua Dwire