How to pass PHP variables in JavaScript or jQuery?

August 20, 2018 | Category : JQuery PHP

Hi Guys,

In this post, we will learn how to access php variable in jquery with small example. We always require to get php array variable or data variable in javascript.

If you have simple string value store on php variable and you require to get in jquery then you can do it easily by using echo of php. But if you need to get array variable then you have to do it using json_encode.

So, just see bellow example and learn how it works:


<!DOCTYPE html>



<title>How to pass PHP variables in JavaScript or jQuery? -</title>




$simple = 'demo text string';

$complexArray = array('demo', 'text', array('foo', 'bar'));


<script type="text/javascript">

var simple = '<?php echo $simple; ?>';


var complexArray = <?php echo json_encode($complexArray); ?>;





I hope it works for you...