1

So I want to store all of my MySQL results in an array I can manipulate with javascript/jQuery.

Here is my current code:

<?php
    $sql = "SELECT * FROM potentials";
    $result = mysql_query($sql) or die(mysql_error());
    $potential = mysql_fetch_array($result);
    echo json_encode($potential);
?>

And my Javascript:

<script type="text/javascript">
    $(document).ready(function(){
        var myArray = "<?php print(json_encode($potential)); ?>";
        console.log(myArray)
    )};
</script>

I keep getting "Unexpected number" or "unexpected identifier". Whats going on?

1
  • it echos out fine, but doesnt console.log in the javascript. Commented Apr 14, 2013 at 15:31

3 Answers 3

2

json_encode() returns an object using JSON notation. Strangely, you surrounded it with quotes. Try removing them :

<script type="text/javascript">
$(document).ready(function(){
    var myArray = <?php print(json_encode($potential)); ?>;
    console.log(myArray);
});
</script>

(and it's not an array, it's an object, so you might want to rename your variable ;) )

3
  • Its now spitting out only the first row of potentials. How to I get all rows? a multidemensional array? what would that look like? maybe a foreach statement? Commented Apr 14, 2013 at 15:39
  • I would go for something like this : <?php $sql = "SELECT * FROM potentials"; $result = mysql_query($sql) or die(mysql_error()); $potential = array(); while($row = mysql_fetch_assoc($result)) { $potential[] = $row; } echo '<script type="text/javascript"> $(document).ready(function(){ var myArray = "' . json_encode($potential) . '"; console.log(myArray) )}; </script>' . "\n"; ?> Commented Apr 14, 2013 at 16:34
  • 1
    Note: replace )}; with }); at line 5 of the answer to prevent 'unexpected token )' bug in console. Commented Feb 5, 2014 at 8:18
0

You are using json_encode() twice, however if you want to use it, you need to parse it. In jQuery this can be done via jQuery.parseJSON like this

var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');

Also if you want all the results, you need to loop the query (e.g. with while) and then save it to an array

$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
    $array[] = $row;
}
1
  • That gives me this in the console: Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON' Commented Apr 14, 2013 at 15:34
0
<script>
    var data = '<?php echo $data; ?>';
    var json = JSON.parse(data);
    console.log(json[0]); //etc
</script>

Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.