August 17, 2013
PHP not working in javascript function
Ceelos’s Question:
Trying out PHP for the first time and I’m really stumped on this. It might be something obvious, but why isn’t my php inside the function checkinfo() working? The alert works fine. Here’s the code
<head>
<script type="text/javascript">
function checkinfo() {
alert("hi");
<?php
echo 'hi';
?>
};
</script>
</head>
<body>
<form id = "form" align = "center">
<div id = "index">
<div id = "unandpw">
Username:
<input type="text">
<br>
Password:
<input type ="password" >
</div>
<!-- end unandpw -->
<div id = "buttons">
<button type = "button" onclick = "checkinfo()">
Login
</button>
<button type = "button" onclick = "register();">
Register
</button>
</div>
<!-- end buttons -->
</div>
<!--index end -->
</form>
</body>
</html>
It gives error, because when the rendered your script becomes this:
function checkinfo() {
alert("hi");
hi
};
Which is an incorrect code. You may be trying to do:
alert("<?php echo 'hi'; ?>");