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

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

share|improve this question
2  
I dont think $data()=[5,10,15,20]; is valid php ??? –  Ronnie Oct 16 at 16:40
 
$data()=[5,10,15,20]; isn't valid PHP. It's close. Please show your actual output, not merely what you think it is. –  Wesley Murch Oct 16 at 16:40
 
the data in php array is good i checked it using echo in php sorry if i inputed the wrong syntax but i just want to show the values in php array –  Jose Samaniego Oct 16 at 16:41
 
@JoseSamaniego No, it is not valid PHP: eval.in/54883 –  ComFreek Oct 16 at 16:41
1  
@TomChew-headMillard There's a new bracket syntax: [1,2,3] vs. array(1,2,3). That's all. –  ComFreek Oct 16 at 16:43
show 4 more comments

2 Answers

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)
}
share|improve this answer
 
By the way, [1,2,3,4,5] is perfectly valid syntax. Only the parentheses were the problem. –  ComFreek Oct 16 at 16:47

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.

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.