daveomcd
daveomcd

Reputation: 6555

AJAX: How can I return an object to jquery?

I'm wondering if I can return an object from json_encode() to JQuery. If I were to do something like this...

$.ajax({
   type : 'POST',
   url  : 'next.php',
   dataType : 'json',
   data     : { nextID : 2 },
   success  : function ( data ) {

            // do something with data.myObject.memberVariable

          },
      error    : function ( XMLHttpRequest, textStatus, errorThrown) {

           //  didn't work!

      }
});     

AND this (next.php)

<?php

include_once('myClass.php');

$myObj = getMyObject( $_POST['nextID'] );  // get an object

$return['myObject'] = $myObj;

echo json_encode($return);

?>

Now I've tested this method but whenever i try to do data.myObject.memberVariable all i get is [object Object]. How can I actually access the variables of the object? Hopefully the code above helps explain my question :(

Upvotes: 0

Views: 8284

Answers (5)

user1404963
user1404963

Reputation: 445

Try this in your JQuery success function:

alert(data.ObjectProperty);

You can access the object's properties using period(.).

Upvotes: 1

Calvin
Calvin

Reputation: 8765

A few pointers/questions:

  1. You should do a print_r($myObj) to make sure that your object is valid and has valid data members. memberVariable is an object itself as SLaks pointed out, and that's why you're getting [object Object].
  2. echo out $return after you've run json_encode() on it and check if the JSON response is valid, and that the member variables you're looking for is correct. JSONLint can format your JSON for easier reading.
  3. How does the getMyObject() function work? When you echo $myObj->m_url does that return anything?
  4. Lastly, you may want to install Firebug if you're using Firefox, or Inspector if you're using a Webkit browser, and use console.log(object) rather than using alert(object). This will give you a more in-depth look at your object rather than [object Object].

Upvotes: 1

Zhasulan Berdibekov
Zhasulan Berdibekov

Reputation: 1087

Maybe parse $myObj on json_encode

Upvotes: 1

SLaks
SLaks

Reputation: 887275

Your memberVariable contains an object.
To see raw data, look at the objects properties:

alert(data.myObject.memberVariable.someProperty);

Upvotes: 1

ajreal
ajreal

Reputation: 47311

How about this ?

 echo json_encode($return['myObject']);

And did you return json header?

Upvotes: 4

Related Questions