0

Trying to pass multidimensional php array to Javascript using JSON. The code refuses to enter the success state of JSON, why is this?

This is javascript file:

array = [];

function callback(arr)
{
 console.log(array);
 //simpleText.setText = array[0]
};
$(document).ready(function() {
 $.getJSON('database.php', function(phpdata){
    console.log("po");
    console.log(phpdata);
    callback(phpdata);
  });

});

And php file:

header("Content-type: application/json");
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("atlas") or die(mysql_error()); 

$data = mysql_query("SELECT * FROM questions") 
or die(mysql_error()); 

$i = 0;
$result_array = array();
 while ($Row = mysql_fetch_array($data)) 
{ 
$user[] = array( 
'id'=>$Row['id'], 
'q'=>$Row['q'],
'a'=>$Row['a'],
'coordx'=>$Row['coordx'],
'coordy'=>$Row['coordy'],
    ); 
} 


var_dump($user);

$json = json_encode($user[0]);


echo $json;
4
  • 2
    Share your JSON with us Commented Nov 22, 2013 at 23:45
  • You're not passing a multidimensional array. You're just passing $user[0], which is one row, which is a one-dimensional array. Commented Nov 23, 2013 at 0:45
  • 1
    You need to take var_dump() out of the script. It will be read by $.getJSON, but it's not valid JSON. Commented Nov 23, 2013 at 0:46
  • As a total side-note, you should use mysql_fetch_assoc and then $user[] = $Row;, save yourself some time and energy by letting the mysql driver do the work for you (us2.php.net/mysql_fetch_assoc) Commented Nov 27, 2013 at 8:49

2 Answers 2

2

Remove the

var_dump($user);

line. It's making the result invalid JSON.

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

Comments

1

getJSON jQuery function does not return errors. Use ajax function below and check your error message and returned JSON (inside jqXHR object):

$.ajax({
    url: 'database.php',
    dataType: 'json',
    success: function(data, textStatus, jqXHR) {
        // success
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // error
    }
});

1 Comment

It seems like i'm getting a SyntaxError{} from the errorThrown, any idea why?

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.