Reputation: 10870
I am trying to assign a json array to a javascript array so that my JS functions can access the array. So I have an ajax call to MySQL db to get a JSON array of data:
var data = [];
$.ajax({
type:"post",
url:"position.php",
dataType:'json',
success:function(jsonarray){
data=$.parseJSON(jsonarray);
}
});
position.php:
<?php
include 'dbconnect.php';
$sql = "SELECT pid, posX, posY FROM posTable;";
$result = $conn->query($sql);
$myrows = $result->num_rows;
$return=array();
if ($result->num_rows>0){
while($row=$result->fetch_assoc()){
$return[]=array((int)$row['pid'],(int)$row['posX'],(int)$row['posY']);
}
}else{
echo "[]";
}
echo json_encode($return);
$conn->close();
?>
This gives an output like this:
[[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
And from this I want the following two dimensional array so that I can access its memebers in this form:
data[i][j]
data => [[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
However when I execute the code I keep getting the following error:
Uncaught SyntaxError: Unexpected token , in JSON at position 1
What am I doing wrong?
Upvotes: 0
Views: 107
Reputation: 943142
jQuery will automatically parse a JSON response before populating the success function's first argument.
$.parseJSON(jsonarray);
calls toString()
on your array and then tries to parse it as JSON, which it isn't (because Array.prototype.toString()
doesn't convert to JSON).
Just don't try to parse it again.
Upvotes: 2