How to access PHP variables in JavaScript or jQuery?

How to access PHP variables in JavaScript or jQuery?

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 :

  1. <?php
  2. $simple = 'demo text string';
  3. $complex = array('demo', 'text', array('foo', 'bar'));
  4. ?>
  5. <script type="text/javascript">
  6. var simple = '<?php echo $simple; ?>';
  7. console.log(simple);
  8. var complex = <?php echo json_encode($complex); ?>;
  9. console.log(complex);
  10. </script>

Phone: (+91) 8800417876
Noida, 201301