5

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_assoc($result)) {
    $dServer[] = $row['model'];
}    

Now, how do I pass the $dServer array into a Javascript array?

For example, this array:

var a = new Array();
4
  • pass all the array from $dServer into a. Commented Apr 19, 2012 at 2:01
  • 3
    Please use the search function. About 1/4 of the questions in the "Related" sidebar answer your question. Commented Apr 19, 2012 at 2:02
  • 1
    @zerkms If they used quotes it would make a a string rather than a variable defined by JSON. Commented Apr 19, 2012 at 2:04
  • @jprofitt: oops, missed that it is not an ajax response, but inline JS Commented Apr 19, 2012 at 2:19

4 Answers 4

15
$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 = <?php echo json_encode($dServer); ?>;
</script>
3

Encode it as a json object.

<?
    $arr = array('entry' => 'content');
?>

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

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 = <?php echo json_encode($dServer);?>;
1

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

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

<script type="text/javascript">
  var a = new Array();

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.