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...
Do you like below Tutorials ?
- Angular Use CKEditor Example Tutorial
- How to Use Multiple Select Dropdown in Laravel?
- Angular 9 Image Upload with Crop Example
- Files Upload on Button Click in PHP Dropzone Example
- PHP Dropzone Allow only One File to Upload Example
- PHP Dropzone Allow only Images to Upload Example
- PHP Dropzone Delete Uploaded File Example
- Livewire CRUD Laravel 7 Example