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!
Type "alert ("Hey, " + name + "!");". This line of code will add the variable "name" to the word "Hey, "(with the space at the end), and then add "!" to end the sentence (not required). For example, if the user inputs "Trevor" as the value of the variable "name", the alert will say "Heya, Trevor!".
PHP doesn't support alert message box because it is a server-side language but you can use JavaScript code within the PHP body to alert the message box on the screen.
Confirm dialog box displays a predefined message with two buttons: OK and Cancel buttons. The user will have to click either of the button to proceed. If the user clicks an OK button, the box returns true to the program. If the user clicks the Cancel button, the box returns false to the program.
The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result.
Display variable php in alert javascript
<?php
function died($error) { ?>
<script>alert("<?php echo $error; ?>")</script>
<?php die();
} ?>
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');
You can use function follow this:
function died($error) {
echo '<script> alert("'.$error.'")</script>';
die();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With