How to call javascript function in php code?

in my login form, I set the checks on the server side, and if an error occurs, I want to display this error just below the approved control. Now for this I am trying to call the javascript function to show the verification message in php code, but I cannot call.

<?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if($_POST['txtUsername']=='') { //here i want to call javascript function to display message } } ?> <form action="login.php" method="POST"> Username <input type="text" size="30" name="txtUsername" id="user" /><br /> Password <input type="password" size="30" name="txtPassword" id="pass" /><br /> <input type="submit" value="Login" name="loginSubmit"/> </form> <script type="text/javascript"> function showMessage(value) { document.getElementById(value).innerHTML= value+"can not be empty."; } </script> 

Please tell me how to display confirmation on the server side just below the approved control in the form.

+4
source share
4 answers

Something like that

 <html> <head> <script type="text/javascript"> function showMessage(value) { document.getElementById(value).innerHTML= value+"can not be empty."; } </script> </head> <body> <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if($_POST['txtUsername']=='') { echo '<script> showMessage("txtUsername"); </script>'; } } ?> <form action="login.php" method="POST"> Username <input type="text" size="30" name="txtUsername" id="txtUsername" /><br /> Password <input type="password" size="30" name="txtPassword" id="txtPassword" /><br /> <input type="submit" value="Login" name="loginSubmit"/> </form> </body> </html> 
+3
source

use this

 if($_POST['txtUsername']=='') { echo '<script> showMessage("txtUsername"); </script>'; } 
+3
source

You can put your php code anywhere as you would like, say in the body as an attribute. You can try the following code:

 <body <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if($_POST['txtUsername']=='') { echo "onload = 'showMessage("VALUE")'"; } } ?> > // end of body start tag <form action="login.php" method="POST"> Username <input type="text" size="30" name="txtUsername" id="user" /><br /> Password <input type="password" size="30" name="txtPassword" id="pass" /><br /> <input type="submit" value="Login" name="loginSubmit"/> </form> </body> <script type="text/javascript"> function showMessage(value) { document.getElementById(value).innerHTML= value+"can not be empty."; } </script> 

If the verification is successful, the php code will not be an echo, and the javascript function will not be called. Works for me :). Tell me if this helps.

+2
source
  <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if($_POST['txtUsername']=='') { ?> <script> //Define the function somewhere in the top or in external js and include it. callyourfunction(); </script> <?php } } ?> //Its not working 
+1
source

All Articles