nilerafter24 nilerafter24 - 1 year ago 62
JSON Question

How can I convert this JSON from PHP to a Javascript array

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 = [];


include 'dbconnect.php';

$sql = "SELECT pid, posX, posY FROM posTable;";
$result = $conn->query($sql);
$myrows = $result->num_rows;

if ($result->num_rows>0){


echo "[]";
echo json_encode($return);

This gives an output like this:


And from this I want the following two dimensional array so that I can access its memebers in this form:


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?

Answer Source

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.