By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,009 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

Call the div displaying error message only when error occurs

P: 19
In this code I am displaying errors with javascript and in case javascript is disabled php will work, error messages are displayed by div at the bottom so whether error occurs or not, div will always be there, though message is displayed only when there is error. I want that the div should be called only when error occurs because it is causing problems to style error message.

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.     $(document).ready(function() {
  3.         $('#submit').click(function() {
  4.             var title = $('#title').val();
  5.             var body = $('#body').val();
  6.             if(title.length<5) {
  7.                 $('#er').html('Error mesg');
  8.                 return false;
  9.             }
  10.             if(body.length<500) {
  11.                 $('#er').html('error msg');
  12.                 return false;
  13.             }
  14.         });
  15.     });
  16. </script>
  17. <?php
  18.     error_reporting('E_ALL ^ E_NOTICE');
  19.     if(isset($_POST['submit'])) {
  20.         $title=$_POST['title'];
  21.         $body=$_POST['body'];
  22.         if (strlen($title) < 5) {
  23.            $er = "Title must be of minimum 5 characters";
  24.         }
  25.         else if (strlen($body) <500 ) {
  26.            $er = "Body must be of minimum 500 characters";
  27.         }
  28.         else {
  29.       // pdo statement to insert data in db
  30.  
  31.         if ($statement->rowCount() == 1) {
  32.            $er = "Congratulations, successfully posted.";
  33.         }
  34.         else {
  35.            print_r($db->errorInfo());
  36.         }
  37.     }
  38. }?> 
  39.  
  40. <form action="" method="post">
  41. <fieldset>
  42. <legend>Write post</legend>
  43. <label>Title:</label> 
  44. <input type="text" name="title" id="title"><br />
  45. <label>Body:</label> 
  46. <textarea name="body" id="body"></textarea><br />
  47. <input type="submit" id="submit" name="submit" value="Post"/>
  48. </fieldset>
  49. </form>
  50. <div id="er"><?php echo $er; ?></div>
I tried replacing div with this code below, but now no error message is displayed seems there is no div.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. if(!empty($er)) {
  3.   echo '<div id="er">'.$er.'</div>';
  4. }
  5. ?>
Oct 29 '15 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.