Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();
share|improve this question
What are you trying to do? – sloopjohnB Apr 19 '12 at 2:00
pass all the array from $dServer into a. – Hafiz Abdullah Apr 19 '12 at 2:01
3  
Please use the search function. About 1/4 of the questions in the "Related" sidebar answer your question. – jprofitt Apr 19 '12 at 2:02
possible duplicate of Best way to pass a 2d array into javascript from php? – Wesley Murch Apr 19 '12 at 2:02
1  
@zerkms If they used quotes it would make a a string rather than a variable defined by JSON. – jprofitt Apr 19 '12 at 2:04
show 1 more comment

4 Answers

up vote 5 down vote accepted
$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>
share|improve this answer

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);?>;
share|improve this answer

Encode it as a json object.

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

<script>
var data = <?=json_encode($arr);?>;
alert(data['entry']);
</script>
share|improve this answer

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.