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!
-
do you want to append the $string and $error variables?Eddie– Eddie2014年04月28日 02:01:35 +00:00Commented Apr 28, 2014 at 2:01
-
Why not use javascript to detect if all the forms are filled in?David Corbin– David Corbin2014年04月28日 02:03:43 +00:00Commented Apr 28, 2014 at 2:03
-
Sorry, I screwed up and added an old version of the code I was using to figure out what was wrong. The $string variable is completely unnecessary. I took it out. Thank you!MarvinLazer– MarvinLazer2014年04月28日 02:03:43 +00:00Commented Apr 28, 2014 at 2:03
-
You just can do a client checking if you just want to 'alert' the error.. but then again the best way to validate is in the server side.Eddie– Eddie2014年04月28日 02:09:15 +00:00Commented Apr 28, 2014 at 2:09
4 Answers 4
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 code to the following (json_encode() the string and create a javascript variable out of it):
function died(string $message) {
if ('' === trim($message)) {
$message = 'died.';
}
?>
<script type="text/javascript">
var message = <?php echo json_encode($message); ?>;
alert(message);
</script>
<?php
die();
}
and you can use your function:
died('error on whatever');
5 Comments
$error. Example: $error = "Another Line \n" . $errorDisplay variable php in alert javascript
<?php
function died($error) { ?>
<script>alert("<?php echo $error; ?>")</script>
<?php die();
} ?>
Comments
You can use function follow this:
function died($error) {
echo '<script> alert("'.$error.'")</script>';
die();
}
Comments
<?php
echo "<script type='text/javascript'>alert('{$_SESSION["success"]}');</script>";
unset($_SESSION["success"]);
?>
Use this code it would work correctly
1 Comment
Explore related questions
See similar questions with these tags.