9

Here's my PHP code called during jQuery AJAX call:

<?php
    include '../code_files/conn.php';
    $conn = new Connection();
    $query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2 
              FROM clients WHERE ID = ?';
    $conn->mysqli->stmt_init();
    $stmt = $conn->mysqli->prepare($query);
    $stmt->bind_param('s', $_POST['ID']);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    echo json_encode($row);
?>

And the client-side code is:

$.post(url, {ID:$('#ddlClients').val()},
        function(Result){
            // Result
        }
      );

The AJAX call is successfully completed. I get the value of Result as

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on

What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.

And I know that this can be done by this code on the server side:

$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);

or

$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);

Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Kumar Kush
  • 2,495
  • 11
  • 32
  • 42
  • 1
    i dont know if you can do that but this might be useful to you. http://stackoverflow.com/questions/383631/json-encode-mysql-results – insomiac Dec 27 '11 at 21:53

3 Answers3

18

The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:

$.ajax({
    url      : url,//note that this is setting the `url` property to the value of the `url` variable
    data     : {ID:$('#ddlClients').val()},
    type     : 'post',
    success  : function(Result){
            var myObj = $.parseJSON(Result);
            //you can now access data like this:
            //myObj.Address_1
        }
    }
  );

You can let jQuery do this for you by setting the dataType property for your AJAX call to json:

$.ajax({
    url      : url//note that this is setting the `url` property to the value of the `url` variable
    data     : {ID:$('#ddlClients').val()},
    dataType : 'json',
    type     : 'post',
    success  : function(Result){
            //you can now access data like this:
            //Result.Address_1
        }
    }
  );

The above examples expect that the response from the server to be in this format (from your question):

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
Jasper
  • 75,717
  • 14
  • 151
  • 146
5

In your $.post call, the last argument could be the data-type: json:

$.post(url, {ID:$('#ddlClients').val()},
    function(Result){
        alert(Result.Address_1);
    },'json'
 );

Everything should work then, as it looks like you are doing everything right.

Jasper
  • 75,717
  • 14
  • 151
  • 146
Tim Withers
  • 12,072
  • 5
  • 43
  • 67
3

json_encode accepts objects, so there's no need to do that automatic array-building.:

$row = $result->fetch_object();
echo json_encode($row);

It's as simple as that!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • You can see my question. I have done that already. What I was missing is that I did not specify type 'json' while making AJAX call. – Kumar Kush Dec 27 '11 at 22:06
  • No, you created the array manually, so I answered the question "Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, _without manually creating an array first?_" – Lightness Races in Orbit Dec 27 '11 at 22:10
  • Sorry, but look at the first block of code in my question. I had tried what you had mentioned also. Both ways, I had to parse the respone in jQuery. Thanks anyways. – Kumar Kush Dec 27 '11 at 22:16
  • Your question is broken then, because the sentence with a question mark apparently isn't anything you really needed help with in the end after all... – Lightness Races in Orbit Dec 28 '11 at 00:43