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 ?
- Laravel 5.6 - Collection could not be converted to int
- Laravel - How to generate secure https URL from route?
- Laravel - Vue JS File Upload Example
- How to get last 7 days data in Laravel?
- Laravel Validation required if other field empty example
- Laravel Eloquent - When Case Statement in Select Query Example
- Laravel 7.x and 6.x Passing Variable to Javascript Example
- How to pass PHP variables in JavaScript or jQuery?