How to access PHP variables in JavaScript or jQuery?
In this post we will give you information about How to access PHP variables in JavaScript or jQuery?. Hear we will give you detail about How to access PHP variables in JavaScript or jQuery?And how to use it also give you demo for it if it is necessary.
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 =<?phpechojson_encode($complex);?>;
- console.log(complex);
- </script>
<?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>This code will work in php file.
Hope this code and post will helped you for implement How to access PHP variables in JavaScript or jQuery?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs