So I’ve searched around a ton and figured out how to pass a PHP variable to a Javascript function, but when I impliment it in my code, rather than getting the variable in the alert(); window I get <?php echo $a ?> and <?php echo $c ?> Hopefully it’s something small that I’m overlooking, but I have no idea why this isn’t functioning as I copied it line for line from a response on a forum and the user stated that it works, and I had a friend who stated that it worked, but when I ran the code on it’s own (Second [code][/code]) it returns the same error.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
$a = 'Fatber Christmas';
$b = '27 Sunshine Street /n America';
$c = nl2br($b);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Kenneth So Photography</title>
<link rel="stylesheet" href="kennethsostylesheet.css" type="text/css">
<link rel="shortcut icon" href="Photos/favicon.png" type="image/png">
<script type="text/javascript">
function test(a,b) {
alert(a);
alert(b);
}
</script>
<script type="text/javascript" src="picScript.js"></script>
</head>
<body>
<a onClick="test('<?php echo $a ?>', '<?php echo $c ?>');">LINK</a>
<div id="headerBar">
<div id="logo">
<a href="javascript:void(0)" ><img src="Photos/FinalizedLogo.png" alt="logo" height="100px" width="400px" onclick="setNum(1)"></a>
</div>
<div id="titleBar">
<p>
<a href="javascript:void(0)" onclick="setNum(1)">Home</a> |
<a href="javascript:void(0)" onclick="setNum(2)">Automotive</a> |
<a href="javascript:void(0)" onclick="setNum(3)">Nightlife</a> |
<a href="/about.html">About Me</a> |
<a href="/contact.html">Contact</a>
</p>
</div>
</div>
<div id="imageBox">
<div id="imageView">
</div>
<div id="imagePreview">
</div>
</div>
</body>
</html>
Stand alone code that results in the same display
<?php
$a = 'Fatber Christmas';
$b = '27 Sunshine Street /n America';
$c = nl2br($b);
?>
<html>
<head>
<script type="text/javascript">
function test(a,b) {
alert(a);
alert(b);
}
</script>
</head>
<body>
<a onClick="test('<?php echo $a ?>', '<?php echo $c ?>');">LINK</a>
</body>
</html>
Thank you guys!!!
Your code is correct as far as the syntax goes, however – as pointed out in the comments – you always need to prepare your variables for the medium you are outputting to (database, other programming language, html, etc.).
The problem is that your php does not get parsed.
The reasons could be:
.htmlinstead of.phpcausing the file not to be recognized as a php file;