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?
 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.