Hello developer In this blog we will see how to access or use PHP variables in to Javascript. Sometime we need to just pass a PHP variable to Javascript on same page.
So here simply set a variable value in PHP and we will use in show a alert in Javascript.
HTML code
In the phpVar variable we set “codermen” value in PHP code.
<h1>Pass PHP Variable to JavaScript</h1>
<?php
$phpVar = "codermen";
?>
Javascript code
Now simply we can use phpVar variable with PHP code in Javascript.
<script type="text/javascript">
var php_var = "<?php echo $phpVar; ?>";
alert(php_var);
</script>
Full code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Pass PHP Variable to JavaScript</h1>
<?php
$phpVar = "codermen";
?>
<script type="text/javascript">
var php_var = "<?php echo $phpVar; ?>";
alert(php_var);
</script>
</body>
</html>

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.