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

PHP object as argument to Javascript function

0
(0)

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.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Leave a Reply

Please disable your adblocker or whitelist this site!