Creating a javascript alert with php that has a php variable inside?
Solution 1
You only forgot quotations that are required for the JavaScript alert.
If you passed 'hello' to the function, your current code would create alert as:
alert(hello)
instead of doing:
alert("hello")
Therefore, change your line to the following (two double quotes are added before and after concatenating $error):
echo '<script type="text/javascript">alert("'.$error.'");</script>';
and you can use your function:
died('error on whatever');
Solution 2
Display variable php in alert javascript
<?php
function died($error) { ?>
<script>alert("<?php echo $error; ?>")</script>
<?php die();
} ?>
Solution 3
You can use function follow this:
function died($error) {
echo '<script> alert("'.$error.'")</script>';
die();
}
MarvinLazer
Front-end/PHP web dev, audio synthesis and music nerd.
Updated on August 16, 2020Comments
-
MarvinLazer over 3 years
I'm making a form that is supposed to create a javascript alert when some fields aren't filled out or filled out properly. I want to be able to take the error messages I've put in a php variable and display them in the javascript alert window.
The following code does not work:
function died($error) { echo '<script type="text/javascript"> alert('.$error.')</script>'; die(); }
How can I add the string contained in
$error
between the two "script" strings so it will output properly as a javascript alert?Thank you!
-
MarvinLazer about 10 yearsThanks! It works, although I don't really understand why. What if I wanted to add other text in the alert that would be concatenated with the variable? Would I have to do something like this? echo '<script>alert('.'Here is some other text!\\n"'.$error.'");</script>';
-
user1978142 about 10 yearsas @frankgorman clearly stated, what happens is that, after you concatenated, you missed the quotes inside rendering the error on javascript. If you want to add, just concatenate another string on
$error
. Example:$error = "Another Line \n" . $error
-
Eon about 9 yearsYou know you are very new to a language when you look for ways to alert/log variables :) (happens that I came to search for this answer too)
-
Scarl over 8 yearsThis displays nothing. As in it does not display the php variable's value for some reason
-
Crickets almost 5 yearsYour answer did not work for me, but this did:
echo '<script>alert("' . $str . '");</script>';
-source -
Giovanni Esposito over 3 yearsCiao, try to add a small explanation. Code-only answer discourages.