Sometimes we need to access the PHP variables in javascript or jquery for the use in the application. In this article, let’s see how to pass data and variables from PHP to JavaScript.
If you have a simple string value in PHP and you want to access that value in javascript or jquery then you have two options to do so.
First, we can pass the data through cookies. In cookies, we can set the data in using PHP cookies and then access that cookies data in JavaScript and jquery.
In the second method, we can simply access the PHP value direct in the JavaScript variable. You only need to initialize the variable in javascript and access the PHP value with all open and close PHP tag inside the Single Quotation mark (”).
Let’s see how we can pass the PHP variable to JavaScript.
Pass PHP variables in JavaScript or jQuery
<?php $output = 'this is dummy text'; ?> <script type="text/javascript"> var output = '<?php echo $output; ?>'; document.write(output); console.log(output); </script>
You can simply check we just defined the value in PHP and then access that variable direct in the JavaScript.
Pass a PHP array to a JavaScript function
<?php $output = array('this', 'text','is good'); ?> <script type="text/javascript"> var output = <?php echo json_encode($output); ?>; document.write(output); console.log(output); </script>
We can easily pass the PHP array to JavaScript, Only need to convert the PHP array to JSON using json_encode function and that can be accessed in the JavaScript.
Pass Multidimensional Arrays from PHP to JavaScript
<?php // PHP array $booksData = array( array( "title" => "title1", "author" => "author1" ), array( "title" => "title2", "author" => "author2" ), array( "title" => "title3", "author" => "author3" ) ); ?> <script type="text/javascript"> var booksData = <?php echo json_encode($booksData) ?>; console.log(booksData); </script>
Conclusion:
It is very easy to pass the data from PHP to JavaScript. We have tried to make you understand with different case scenarios that must have helped you to understand all.
If you have any queries related to this post, please comment below i would love to help you.
You can also check How to get a random key from a PHP array