Reputation: 23
I am trying to pass a JSON object from PHP to Javascript. the object is being filled from an SQL Database here is the PHP code I am using.
<?php
$conn = mysql_connect("localhost","root","");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db') or die( 'Error'. mysql_error() );
$query = "SELECT * FROM products;";
$results = mysql_query($query, $conn);
$return = array();
while($result = mysql_fetch_assoc($results))
{
$mount = array('product_code' => $results['product_code'], 'colour' => $results['colour'], 'price' => $results['price']);
array_push($return, $mount);
}
return json_encode($return);
?>
I have changed a few of the variable names but the same functionality is there.
now when I try to do an AJAX Get to this .php file it crashes at the JSON.Parse part code shown below:
$.get("JSON.php", function(data) {
var JSONdata = JSON.parse(data);
alert(JSONdata[0].colour);
});
My alert is there just for testing. I Understand the problem may lie in my building of the $return array. Rather new to JSON, any help would be greatly appreciated.
EDIT: taking all the information from below I have corrected my PHP code to look as such.
<?php
$conn = mysql_connect("localhost","root","");
$error = array("result" => false, "error" => mysql_error());
if(! $conn )
{
die(json_encode($error));
}
mysql_select_db('db') or die(json_encode($error));
$query = "SELECT * FROM products;";
$results = mysql_query($query, $conn);
$return = array();
while($result = mysql_fetch_assoc($results))
{
$mount = array('product_code' => $result['product_code'], 'colour' => $result['colour'], 'price' => $result['price']);
array_push($return, $mount);
}
echo json_encode($return);
?>
I'm Looking into changing the mysql_* functions to new more compatible versions
Upvotes: 0
Views: 2895
Reputation: 5847
You are using 'return' at the end of the php script, echo the json encoded string :
echo json_encode($return);
Also, it might be a good idea to set the contenttype header to application/json.
Edit:
If you script fails, you use die('error'.mysql_error());
This will also be a response to the ajax call, but not json, and the parse function will throw an exception.
I would recommend returning a json object instead, like:
$error = array("result" => false, "error" => mysql_error());
die(json_encode($error));
Also as stated in comments, do not use mysql_* functions, they are deprecated in later php versions and will be gone from php all together in future releases.
Check out mysqli or even better, PDO.
Upvotes: 4