Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a PHP Class object to Javascript and accessing its properties in Javascript function

Tags:

javascript

php

I'm having trouble accessing the properties of an object within a Javascript function I created. The object is originally a PHP object which I encoded as JSON using json_encode()

I have 1 PHP file and 1 external JS file.

In my PHP file, I have the ff:

<?php
    $announcementDaoImpl = new AnnouncementDaoImpl($pdo);
    $announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
    foreach($announcementList as $key => $value): ?>
        <tr>
        <td><?php echo $value->getId(); ?></td>
        <td><?php echo $value->getTitle(); ?></td>
        <td><?php echo $value->getDateAdded(); ?></td>
        <?php echo json_encode($value); ?> 
        <td>
        <a href="#" onclick="showEditModal('modalBox',<?php echo json_encode($value); ?>)">Edit</a>
        </td>
        </tr>
    <?php endforeach; ?>

I am able to get and display the values by using the get() methods on the <td>'s. However, when I encode it to JSON via json_encode($value), I get nothing.

Line

<?php echo json_encode($value); ?> 

echoes {} {} {} {} {} {} {} {} {} {} {} {} {} which seems to be empty objects.

My goals are to be able to pass the $value php object to the javascript method showEditModal() then access the object's properties within the method block. Something like, object.propertyname

Below is the javascript method showEditModal() implementation.

function showEditModal(modalDivId,object){
    alert(object.title); //returns undefined

    var modalBox = document.getElementById(modalDivId);
    var modalContentValues = document.getElementById("modalContentValues");
    modalBox.style.display = "block";
    var node = document.createElement("p");
    var text = document.createTextNode(object); //shows [object Object]
    node.style.display = "inline";
    node.appendChild(text);
    modalContentValues.appendChild(node);
}

--- EDIT ---

Here's the class definition.

class Announcement {
    private $id;
    private $title;
    private $content;
    private $dateAdded;


    public function getContent()
    {
        return $this->content;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }

    public function getDateAdded()
    {
        return $this->dateAdded;
    }

    public function setDateAdded($dateAdded)
    {
        $this->dateAdded = $dateAdded;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }
} 

-- end of edit --

This is what displays on my browser.

enter image description here

I've added some comments to the javascript method for additional details.

I'd appreciate any help.

Thank you.

like image 799
heisenberg Avatar asked Nov 24 '25 10:11

heisenberg


1 Answers

You can implement the JsonSerializable interface to define what properties you want to make visible when you serialise an object; e.g:

<?php 

class User implements \JsonSerializable
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function jsonSerialize()
    {
        return [
            'name' => $this->name,
        ];
    }
}

echo json_encode(new User('Bob')); // {"name":"Bob"} 

This is an idiomatic way to handle object serialisation in PHP in a transparent and implicit manner, and it allows you to define a preferred shape/format for the json respresentation of your object and encapsulate it within its class definition.

It's quite handy when serialising nested object structures, for example, when you were using value objects - here's a (contrived) example:

class Latitude implements \JsonSerializable
{
    private $degree;

    public function __construct(float $degree)
    {
        // validation etc.
        $this->degree = $degree;
    }

    public function jsonSerialize(): float
    {
        return $this->degree;
    }
}

class Longitude implements \JsonSerializable
{
    private $degree;

    public function __construct(float $degree)
    {
        // validation etc.
        $this->degree = $degree;
    }

    public function jsonSerialize(): float
    {
        return $this->degree;
    }
}

class Coordinate implements \JsonSerializable
{
    public function __construct(Latitude $latitude, Longitude $longitude)
    {
        $this->latitude = $latitude;
        $this->longitude = $longitude;
    }

    public function jsonSerialize(): array
    {
        return [
          'latlng' => [$this->latitude, $this->longitude],
        ];
    }
}

$coordinate = new Coordinate(new Latitude(0), new Longitude(0));

echo json_encode($coordinate); // {"latlng":[0,0]} 

Example: https://repl.it/repls/RelievedLightcyanFolders

like image 187
Darragh Enright Avatar answered Nov 27 '25 00:11

Darragh Enright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!