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?

Emmanuel N K
  • 8,710
  • 1
  • 31
  • 37

1 Answers1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 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] – Emmanuel N K Jun 02 '16 at 09:54
  • `console.log` is the usual choice for inspecting an element – Quentin Jun 02 '16 at 09:55
  • 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 – Emmanuel N K Jun 02 '16 at 09:56
  • Are you sure you get an undefined **error** and not just an alert where the value is a stringified `undefined` value? – Quentin Jun 02 '16 at 10:00
  • I get : **Cannot read property '0' of undefined** Alert does not pop up – Emmanuel N K Jun 02 '16 at 10:02
  • It's hard to tell without more context. This does seem to be a different problem though, so I suggest that you ask a new question with a http://stackoverflow.com/help/mcve showing how you are running that code and when. – Quentin Jun 02 '16 at 10:04
  • It now works when I place the for loops inside the ajax call (within the success function). I have no idea why this is yet I defined **data** outside the ajax call. – Emmanuel N K Jun 02 '16 at 10:10
  • Amazing find and answer, that one! +1 – Emmanuel N K Jun 02 '16 at 10:29