Send PHP object as an argument to Javascript function - onclick event

Send PHP object as an argument to Javascript function

Suppose you have a PHP variable or an object which you want to pass to a Javascript function whenever a button is clicked. Following this tutorial, you will be able to do so.

We will not be directly sending the PHP variable, but instead we will attach the PHP variable to the HTML tag attribute and then send that tag to the Javascript function.

    $variable = "Adnan";

    $object = new \stdClass();
    $object->my_value = 2021;

<button type="button"
    data-variable="<?php echo $variable; ?>"
    data-object="<?php echo htmlentities(json_encode($object)); ?>"

    function buttonClicked(self) {
        var variable = self.getAttribute("data-variable");

        var object = self.getAttribute("data-object");
        object = JSON.parse(object);

You can see that we are sending a simple PHP variable to the Javascript function when the button is clicked. We are also sending a complete PHP object too. PHP objects can be sent by first converting them into JSON string format. Then we will convert the JSON string characters into HTML entities.

And on Javascript side, we simply have to parse the JSON string back into Javascript array or object. If you face any problem in implementing this in your project, please do let us know in the comments section.

Leave a Reply

Please disable your adblocker or whitelist this site!