0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I now assigned jsonarray to data without the json parsing and it takes care of the error. How can I see that data is now properly two dimensional? i.e. how can I see that data is truly of the form data[i][j]
console.log is the usual choice for inspecting an element
When I try this, I get 0 undefined error: ` for(var i=0;i<2;i++){ for(var j=0;j<3;j++){ alert(data[i][j]); } }` UPDATE: From console I can see that data is indeed a 2D array
Are you sure you get an undefined error and not just an alert where the value is a stringified undefined value?
I get : Cannot read property '0' of undefined Alert does not pop up
|

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.