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:

Example:

<!DOCTYPE html>

<html>

<head>

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

</head>

<body>

<?php

$simple = 'demo text string';

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

?>

<script type="text/javascript">

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

console.log(simple);

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

console.log(complexArray);

</script>

</body>

</html>

I hope it works for you...