PHP is server side language which retrieves data from database and show in client side. Javascript is client side language which manipulate HTML and data receives from server. So it obviously that you need to pass PHP data into Javascript variables and function.
In this article, we will discuss on how you can pass PHP variables to Javascript and use it into Javascript function. To do that, you can simply use echo()
function into Javascript variable value.
<?php
$message = "Hello World!"; // here you get data from database
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP variable to JavaScript</title>
</head>
<body>
<h1>PHP variable to JavaScript</h1>
<script type="text/javascript">
var message = "<?php echo"$message"?>";
alert(message);
</script>
</body>
</html>
If the PHP data is array or object, first you need to convert it to Json object using json_encode()
function. Then you can easily manage Json object in Javascript.
<?php
$fruits = ['orange' => 'mango', 'yellow' => 'banana', 'red' => 'apple'];
$json_fruits = json_encode($fruits);
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP variable to JavaScript</title>
</head>
<body>
<h1>PHP variable to JavaScript</h1>
<script type="text/javascript">
var fruits = <?php echo($json_fruits)?>;
alert(fruits.yellow);
</script>
</body>
</html>
This way, you can pass data from server-side to client-side and manage.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
John the Ripper Installation and Crack Password
John the Ripper is a free, most pop...Change Password with Current Password Validation in Laravel
Today, we will learn to update password...Laravel 5.5 - simple crud operation with example
Today, we are sharing how to make s...Laravel 8 Instamojo Payment Gateway Integration
Today we visually perceive How to integr...GET and POST requests using Python requests module
Requests is open-source library to send...