Gnp Pat
Gnp Pat

Reputation: 9

using a php variable in a JS funcion

i previously asked this question but the example i provided did not provide my real problem.

I want to get the input from a form using a php variable and use it in a javascript function. I do not use javascript directly because the content of the variable in question is obtained from a mysql database and i do not think that there is a way for me to access the database using javascript.

below its the code that i have so far:

<!DOCTYPE html>
<html>
  <head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

<script>
function initialize() {
    var slon1 = '<?php echo (json_encode($siteLon1)); ?>';  
    self.alert(slon1);

    //some code goes here.
}
</script>

</head>
  <body>
        <div align="center">
     <form method="get">
        <label>Choose Site</label>
        <select name='ps' id="ps" data-inline="true">
                        <?php
                            $use = $fgmembersite->getsites($fgmembersite->UserFullName());
                            $fields_num = mysql_num_fields($use);

                            while($row = mysql_fetch_row($use))
                            {
                                echo "<option value='".$row[0]."'>".$row[0]."</option>";
                            }
                        ?>
         </select>
         <input type="submit" name="submit" value="View">
     </form>
     </div>   
    <div id="map-canvas"></div>

  </body>
</html>

Suprisingly enough, the result displayed on self.alert(slon1) is null; be it when i just load the page or when choose from the drop down box and click on View. Please someone help me on this.

Thanks.

Upvotes: 0

Views: 80

Answers (1)

JSON encoder should quote variable, so using single quotes manually would trigger JavaScript parse error. Check JS console. This should generate valid JS code:

var slon1 = <?php echo (json_encode($siteLon1)); ?>;

Upvotes: 1

Related Questions