tags:

views:

18

answers:

1

Hi all,

I was trying to use JQuery AJAX to grab some data retrieved from the database in cakePHP 1.26:

 function testing(){
    $user = $this->user->findallbyuser_id("1");
    return $user;
}

and here is the output from cakePHP built-in function Debug($user):

Array
(
    [user_id] => 1
    [name] => hello  
)

Here is the JQuery part:

  $.ajax({
      type: "POST",
      url: curl,   
      success: function(data){ 
      alert(data); }
});

Here is the Alert message:

Array <!--0.082-->

Later, I found that the Alert message showed me something different after I altered the code:

 function testing(){
    $user = $this->user->findallbyuser_id("1");
    return json_encode($user);
}

And here is the new output from the Alert message box:

{"user_id":"1","name":"hello"}<!--0.0953-->

But I don't know how to print out the data returned from JQuery AJAX in this way:

User ID: 1
User name: hello
+2  A: 

JSON can be thought of as simply a PHP array for JavaScript (it's not that strictly speaking, but it helps to understand).

So to get the value of user_id we do the following

$.ajax({
    type: "POST",
    url: curl,   
    success: function(data) { 
        alert(data.user_id); 
    }
});

Notice how we simply append .user_id because thats the key name from the JSON array.

When the PHP script returned the JSON encoded array, jQuery.ajax picked it up and popped it into the data variable we defined via success: function(data){}

jakeisonline