Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
4  
put alert(JSONdata[0].colour); before you parse. And usually, we need to print response to JSON request, not return it. –  user4035 Sep 17 '13 at 9:11
3  
Please, do not use the mysql_* functions anymore. With the release of PHP 6 they will be deprecated. Look into the PDO object in PHP! –  stUrb Sep 17 '13 at 9:15
 
@stUrb They are already deprecated. You mean removed. –  Marty Sep 17 '13 at 9:35
 
thank you for the heads up and surely you need to parse the data before it can be used in the alert? –  Phil Sep 17 '13 at 10:03
 
@MartyWallace that's indeed what I meant :) –  stUrb Sep 17 '13 at 14:17
add comment

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
 
Thanks for the update on mysql_* functions, will change accordingly. i have taken your advice and replaced the die methods, also I must have been in .net mode for the return, that has been corrected to print_r now. I have commented out the parse and added alert(data) and now i am getting a parse error "Syntax error, unexpected T_STRING in filename at line 21" that being the new print_r line. ps. i also added the content-type now thank you for reminding me. –  Phil Sep 17 '13 at 10:21
 
just noticed as well that I am using $results and not $result within the while loop but I still get the same error after correction. –  Phil Sep 17 '13 at 10:31
 
How does line 21 look? –  Jite Sep 17 '13 at 11:00
 
Print_R json_encode($return); i have not changed it to an echo and it works. –  Phil Sep 17 '13 at 11:27
 
Perfect, glad I could help :) –  Jite Sep 17 '13 at 11:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.