Skip to content Skip to sidebar Skip to footer

Pass Php Array Into Javascript Array

Referring to the title. I have an array which I coded like this:- $query = 'SELECT * FROM server'; $result = mysql_query($query); $dServer = array(); while($row = mysql_fetch_asso

Solution 1:

$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();

while($row = mysql_fetch_assoc($result)){
    $dServer[] = $row['model'];
}    

?>
<script type="text/javascript">
    var a = <?phpecho json_encode($dServer); ?>;
</script>

Solution 2:

Encode it as a json object.

<?$arr = array('entry' => 'content');
?><script>var data = <?=json_encode($arr);?>;
alert(data['entry']);
</script>

Solution 3:

Try to get use of ajax request and json_encode.

Second variant

<?php$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();

     while($row = mysql_fetch_assoc($result))
      {
              $dServer[] = $row['model'];
      }    
?>var a = <?phpecho json_encode($dServer);?>;

Solution 4:

In addition to the ajax / json methods mentioned, you can directly print out the values:

<?php$query = "SELECT * FROM server";
  $result = mysql_query($query);
?><scripttype="text/javascript">var a = newArray();

<?phpwhile($row = mysql_fetch_assoc($result)){
    echo"a['model'] = " . $row['model'] . ";"; 
    echo"a['nextField'] = " . $row['nextField'] . ";"; 
  }
?></script>

Post a Comment for "Pass Php Array Into Javascript Array"