Reputation: 6555
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
Reputation: 445
Try this in your JQuery success function:
alert(data.ObjectProperty);
You can access the object's properties using period(.).
Upvotes: 1
Reputation: 8765
A few pointers/questions:
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]
.$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.getMyObject()
function work? When you echo
$myObj->m_url
does that return
anything?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
Reputation: 887275
Your memberVariable
contains an object.
To see raw data, look at the objects properties:
alert(data.myObject.memberVariable.someProperty);
Upvotes: 1
Reputation: 47311
How about this ?
echo json_encode($return['myObject']);
And did you return json header?
Upvotes: 4