0

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

5
  • 4
    put alert(JSONdata[0].colour); before you parse. And usually, we need to print response to JSON request, not return it. Commented Sep 17, 2013 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! Commented Sep 17, 2013 at 9:15
  • @stUrb They are already deprecated. You mean removed. Commented Sep 17, 2013 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? Commented Sep 17, 2013 at 10:03
  • @MartyWallace that's indeed what I meant :) Commented Sep 17, 2013 at 14:17

1 Answer 1

4

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.

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

4 Comments

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.
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.
How does line 21 look?
Print_R json_encode($return); i have not changed it to an echo and it works.

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.