I'm trying to pass a string variable through the parameter of a php function called alertText to a javascript function called alert, to alert a message to the screen, but it's not accepting the php variable for some reason, and nothing is being alerted to the screen. Please take a look:
testing.php
function alertText($text) {
echo "
<script>
alert($text);
</script>
";
}
alertText("Hello");
?>
4 Answers 4
You need to single-quote the $text variable, because JavaScript is not recognizing that variable as string.
<?php
function alertText($text) {
echo "<script>alert('$text');</script>";
}
alertText("Hello");
Comments
You could concatenate it to get a more readable code.
function alertText($text) {
echo "<script>alert('".$text."');</script>";
}
alertText('Hello');
Comments
Very simple mistake, you forgot to close the double quote letting the parser know that $text is not the word $text (hey it could happen!).
We use .$variable_name. to concatenate the value of the variable with the javascript function at runtime.
<?php
function alertText($text) {
echo "
<script>
alert('".$text."');
</script>
";
}
alertText("Hello");
?>
** EXAMPLE CORRECTED **
Comments
You should use it like
function alertText($text) {
echo '<script type="text/javascript">alert("' . $text . '"); </script>';
";
}
alertText("Hello");
?>