In this post, I will tell you how to access PHP variables in JavaScript or jQuery.
Most of the time you will need to access php variables inside jquery or javascript.
If you have simple string value then you can echo this in javascript directly but if you have array type of value and you want to get it in javascript then you have to use json encode method.
See the example below :
- <?php
- $simple = 'demo text string';
- $complex = array('demo', 'text', array('foo', 'bar'));
- ?>
- <script type="text/javascript">
- var simple = '<?php echo $simple; ?>';
- console.log(simple);
- var complex = <?php echo json_encode($complex); ?>;
- console.log(complex);
- </script>