PHP object as argument to Javascript function

Suppose you have a PHP variable or an object which you want to pass as an argument 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.

<?php
    $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)); ?>"
    onclick="buttonClicked(this);">Button</button>

<script>
    function buttonClicked(self) {
        var variable = self.getAttribute("data-variable");
        console.log(variable);

        var object = self.getAttribute("data-object");
        object = JSON.parse(object);
        console.log(object.my_value);
    }
</script>

When the button is clicked, we are sending a PHP object to the Javascript function as an argument. We are also sending a complete PHP object too. PHP objects can be sent by first converting them into JSON string format. You can learn more about the htmlentities function from PHP official documentation. Then we will convert the JSON string characters into HTML entities.

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

You can also check our more tutorials on PHP.

[wpdm_package id=’1217′]