Hi,
I am trying to pass a variable to a javascript function “show_alert” using the following code. It seems like missing something here. If someone can point out what is the wrong with the “show_alert(<?php echo $test_message; ?>” in the code, it’d be very helpful.
Thanks again!
<?php
$test_message= ‘This is a test message’;
?>
<html>
<head>
<script type=“text/javascript”>
function show_alert(msg)
{
alert(msg);
}
</script>
</head>
<body>
<input type=“button” onclick=“show_alert(<?php echo $test_message; ?>)” value=“Show alert box” />
</body>
</html>
That would result in
show_alert(This is a test message);
I’m guessing it might work better with quotes?
When i click on the button, no alert window came out. What is the correct way to pass a PHP variable into my javascript function in the onclick?? Please help!
PHP outputs text to the browser, that is all. The browser interprets that text as HTML and Javascript etc, however you tell it to interpret it. That is all that happens, it isn’t a case of bridging two languages.
View the HTML source in your browser, what is output? What should it be?
When i view the HTML code from the browser, it shows
<input type=“button” onclick=“show_alert(<?php $test_message; ?>)” value=“Show alert box” />
So PHP did not execute the “<?php $test_message; ?>”. Any clue??
Does the file have the “.php” extension?
Either the server isn’t set up to parse PHP or you’re not accessing the file through the server.
I double checked it and everything else works fine. Just this small test_alert.php. I’m using EasyPHP and access it in the URL
http://127.0.0.1:8888/site3/test_alert.php
If i added the quote around “<?php ?>”.
show_alert(‘<?php echo $test_message; ?>’)
The alert window shows “<?php echo $test_message; ?>”. Can someone try it in your environment? I ran out of ideas here.
Thanks!!!
Luckily I’ve never had to mess with ports all that much. But I’m wondering if using that port by-passes the PHP parser for some reason. Does it work if you leave out the “:8888” ?
No, it doesn’t work.
Other scripts work just fine under that port.
A puzzler all right.
If you change
<input type="button" onclick="show_alert(<?php echo $test_message; ?>)" value="Show alert box" />
to simply
<?php echo $test_message; ?>
does it render “This is a test message”
or “<?php echo $test_message; ?>” ?
After i recreate another PHP file and retyped in the code, it works fine now. The original file size was twice bigger than the new one. I am assuming there was something in there that prevented PHP from parsing the PHP code.
Thanks again.