up vote 1 down vote favorite
share [fb]

I would like to know if we can select data from the database using php and assign it to a javascript array? if so what would be the syntax?

I wrote the code below but it is not working

$js_array = "[";
$result = mysql_query("SELECT item_name FROM tbl_item");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
    $js_array .= $row[0]; 
    $js_array .= ",";
}
$js_array{ strlen($js_array)-1 } = ']';

 ?>

<script>
var cities = <?php echo  $js_array; ?>
for(var i=0; i<4;i++)
alert(cities.length);

</script> 
link|improve this question

61% accept rate
You should manually build JSON. Have a look at the output. You will create something like [name1, name2, name3] which will result in an error because nameX are undefined variables. – Felix Kling Jun 30 at 8:46
feedback

3 Answers

You should not echo the array object.

Iterate the array and echo the value.

<?php foreach( $js_array as $value) echo "'$value',"; ?>
link|improve this answer
This doesn't work in IE because of the trailing comma. You will have to work around this complicately or use implode(). – Boldewyn Jun 30 at 8:48
feedback

The simplest approach is converting to JSON with json_encode:

// with $js_array being a true array
var cities = <?php echo json_encode($js_array)?>;

Note, that there are esoteric cases, where this solution might not work. On the other hand, the advantage is, that json_encode takes over all quoting needs.

link|improve this answer
feedback

Use json_encode

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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