Sergio B
Sergio B

Reputation: 734

Returning row from PHP to jQuery

I'm a newb to the whole PHP, jQuery (Ajax), Mysql stack, and I can't figure this out.

I have some PHP code making a call to Mysql and returning one row, in that same page I read the json being returned from php into jquery and I use the JSON.parse function and I can retrieve the information in that object like this: client.firstname, client.lastname and so on.

PHP:

        $query="SELECT * FROM clients WHERE  clientid='$clientid'";
        $result=mysqli_query($con,$query) or die(mysql_error());
        $num_rows=mysqli_num_rows($result);         
        $row = mysqli_fetch_array($result);
        $client=json_encode($row);

jQuery:

$(document).ready(function() {
    data='<?php echo $client?>';
    client=JSON.parse(data);
    $("#company").val(client.company);
    $("#firstname").val(client.firstname);
});

However my problem begins when I try to make an ajax call to a PHP file which executes the same query, and returns the same data. Once I receive the json object on the ajax call I can print it out and see I am receiving the row back, but as soon as I call the JSON.parse(data) function I get an error message

PHP:

$query="SELECT * FROM clients WHERE  clientid='$clientid'";
$result=mysqli_query($con,$query) or die(mysql_error());
$num_rows=mysqli_num_rows($result);         
$row = mysqli_fetch_array($result);
$client=json_encode($row);
echo $client; //this is the only different line

jQuery

$.ajax({
    type: "POST",
    url: "ClientDetails.php",
    data: "clientid="clientid,
    datatype: "json",
    success: function(data){
        client=JSON.parse(data);
        $("#company").val(client.company);
        $("#firstname").val(client.firstname);
    }
});

Once I run it I get this error message in Firebug:

SyntaxError: JSON.parse: unexpected character

Not sure what I'm doing wrong, any help is greatly appreciated.

Upvotes: 1

Views: 551

Answers (1)

Kevin B
Kevin B

Reputation: 95055

You don't need to parse it, jQuery does that for you since you specified the dataType.

success: function(client){
    //client=JSON.parse(data);
    $("#company").val(client.company);

Upvotes: 2

Related Questions