Jose Samaniego
Jose Samaniego

Reputation: 110

php array to javascript objects

hi there im having a problem adding values to my graph from php array to javascript object so far i have a php values in the array

$data=array(5,10,15,20);

and i converted it to json to prepare for javascript

$js_array = json_encode($data);

and heres the javascipt part

data : <?php echo json_encode( $data ); ?>

i think it is reading it as

data : [5] or data : [5101520]

it was suppose to read it as

data : [5,10,15,20]

thanks guys hoping you can help me

here is the php array storing

<?php  
$data = array();

$que = "SELECT name FROM table1 ORDER BY date ASC";

$res = mysql_query($que, $con);

if(mysql_num_rows($res)>0){

while($row = mysql_fetch_array($res)){

$data[] = $row['name'];

}}

$js_array = json_encode($data);

?>'

here is the var dump data echo array(4) { [0]=> string(1) "5" 1=> string(2) "10" [2]=> string(2) "20" [3]=> string(2) "15" }

here is the current output

Upvotes: 2

Views: 139

Answers (2)

Nishu Tayal
Nishu Tayal

Reputation: 20830

The way you have defined php array will throw syntax error.

Use like this :

<?php
$data=array(5,10,15,20);
print_r(json_encode($data));
?>

It'll give you output :

data : [5,10,15,20]

Here is the demo : http://codepad.org/UVFT6m67

Now you can use this json object with your javascript.

Upvotes: 0

ZiTAL
ZiTAL

Reputation: 3581

php

// array
$data = array(1,2,3,4,5);
// array -> json
$json = json_encode($data);
// print json
echo $json;

js with jquery:

$.getJSON( "script.php", function( data ) {
console.log(data)
}

Upvotes: 3

Related Questions