Rick Bross
Rick Bross

Reputation: 1082

MySQL/PHP Array to Javascript

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?

Upvotes: 1

Views: 11702

Answers (3)

&#220;ber
&#220;ber

Reputation: 44

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 ;) )

Upvotes: 2

davetoxa
davetoxa

Reputation: 265

<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

Upvotes: 0

kero
kero

Reputation: 10638

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;
}

Upvotes: 0

Related Questions