0

How to handle a array response from .getjson. Following code handles ajax request.

function getinfo()
 {
     $query="select field_uname_value,field_uaddress_value,field_uphone_value from {content_type_udetails}";
     $result= db_query($query);
     $i=0;     
     while($item = db_fetch_object($result))
     {
      $info[$i++]=array($item->field_uname_value,$item->field_uaddress_value,$item->field_uphone_value);
     }
     print_r($info);
 }

and returns array as follows

Array
(
    [0] => Array
        (
            [0] => bharath
            [1] => 12th street ,ram nagar
            [2] => 213124442
        )

    [1] => Array
        (
            [0] => Christina
            [1] => 77,five corner
            [2] => 76874323
        )

    [2] => Array
        (
            [0] => Ranjan
            [1] => queen towers, 4th layout
            [2] => 45745747
        )

)

but following ajax handling not works. how to get the array response

 $.getJSON('/knpgetuserinfo.json&timestamp'+new Date().getTime(), function(data) {
   alert(data[0][0]); 
}
0

2 Answers 2

2

You cant do that, print_r just prints teh array to readable text, you still some key/value separation form in there, and as your using getJSON i would say that you use json_encode()

function getinfo()
    {
        $query="select field_uname_value,field_uaddress_value,field_uphone_value from {content_type_udetails}";
         $result= db_query($query);
         $info = array();
         while($item = db_fetch_object($result))
         {
             $info[] = array(
                 'name' => $item->field_uname_value,
                 'address' => $item->field_uaddress_value,
                 'phone' => $item->field_uphone_value
             );
         }
         echo json_encode($info);
     }

and then use javascript like so:

$.getJSON('/knpgetuserinfo.json&timestamp'+new Date().getTime(), function(data) {
    $.each(data,function(item){
       //use item.name or item.address here
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of printing, you need it in JSON format via json_encode, by replacing:

print_r($info);

With:

echo json_encode($info);

The problem is you're not returning the data in a JSON format currently, so when jQuery goes to parse, it fails.

2 Comments

the json_encode returns a string, not an object of any type in PHP, should just be echo'd !
@RobertPitt - Yup, when I slapped his code in a quick test it reminded me, already updated :)

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.