We help IT Professionals succeed at work.
Get Started

Question about PHP and JSON

elepil asked
Last Modified: 2015-04-19
Let's say I'm using Ajax to receive a JSON object from a PHP script. From the examples I've seen, people invariably use an array and json_encode() it, then pass it back to the page:

// Inside the PHP script
$arr = ['firstName'=>'John', 'lastName'=>'Doe'];
echo json_encode($arr);

Open in new window

Is it possible to json_encode() a custom class? Because I created a custom User data object class, then json_encode() it and pass it back like the above example, and JavaScript does receive it as [object Object], but I can't get anything out of it. I tried using JSON.stringify, it comes up empty.

So is the PHP array the only vehicle I can use to pass JSON data from the server?
Watch Question
Most Valuable Expert 2011
Author of the Year 2014
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE