Question about PHP and JSON

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?
elepilAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
The JSON standard.
http://json.org/

About anything at all can be represented in JSON.  It's better than PHP serialized objects for a bunch of rather arcane reasons, and it's become my goto data representation for all kinds of data communications.

You cannot expect a good result if you JSON-encode a class but you can JSON-encode an object.

<?php // demo/json_object.php
error_reporting(E_ALL);

class Employee
{
    public $name;
    public $surName;
    public $salary;

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function setSurname($surname)
    {
        $this->surName = $surname;
        return $this;
    }

    public function setSalary($salary)
    {
        $this->salary = $salary;
        return $this;
    }

    public function asJson()
    {
        return json_encode($this);
    }
}

// Create a new object instance of the Employee class:
$employee = new Employee();

// Employee Tom Smith has a salary of 100:
$employee->setName('Tom');
$employee->setSurname('Smith');
$employee->setSalary('100');

// SHOW THE JSON REPRESENTATION
echo $employee->asJson();

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
elepilAuthor Commented:
That's a big nugget to me! Thanks, Ray!
0
Ray PaseurCommented:
Here's a little more complete example.

Client side code:
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>Ajax Example Using jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){
    $("#signal").click(function(){
        $.get("json_object_server.php", function(jso){
            var obj = JSON.parse(jso);
            $("#output p#target").html(obj.name + ' ' + obj.surName);
            alert('Salary: ' + obj.salary);
        });
    });
});
</script>

</head>
<body>

<div   id="signal">Click Me to Trigger AJAX</div>
<div   id="output">
   <p  id="target">This element gets the AJAX response</p>
</div>

</body>
</html>

Open in new window


Server side code:
<?php // demo/json_object_server.php
error_reporting(E_ALL);

class Employee
{
    public $name;
    public $surName;
    public $salary;

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function setSurname($surname)
    {
        $this->surName = $surname;
        return $this;
    }

    public function setSalary($salary)
    {
        $this->salary = $salary;
        return $this;
    }

    public function asJson()
    {
        return json_encode($this);
    }
}

// CREATE A NEW OBJECT INSTANCE OF THE EMPLOYEE CLASS:
$employee = new Employee();

// EMPLOYEE TOM SMITH HAS A SALARY OF 100:
$employee->setName('Tom');
$employee->setSurname('Smith');
$employee->setSalary('100');

// SHOW THE JSON REPRESENTATION
echo $employee->asJson();

Open in new window


Link: http://iconoun.com/demo/json_object_client.php
0
elepilAuthor Commented:
I didn't know about JSON.parse. I would've just set my .ajax()'s dataType attribute to "json", and then in the .done()/.success() handler, I would just treat the returned object as a JSON object. But now I know an alternative!

I'd give you more points, but I've already assigned points. But I hope you'll take gratitude points instead. Thank you very much, Ray!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.