0

My question is how do I stop modal from closing, on two occasions, when user clicks the sign up button:

  • if the inputs are invalid? and display PHP error message
  • inputs are valid and to display PHP success message for couple of seconds before closing modal?

for the first case if I reopen the modal I can see the validation error messages which are displayed by PHP.

I have checked this similar question but haven't figure it out how to do it in my case yet so any help will be much appreciated. I would like to fully understand what is going on and what I am doing.

So far after reading here and there I noticed that this can probably be achieved by:

  • JQuery / JavaScript to do the form validation and not to use PHP
  • some people suggested using iframe

Is there a way to use the PHP code below and display error / success messages from this code? or it has to be done via JQuery/JS?

My PHP with HTML code

<?php 
ob_start();
include('header.php');
include_once("db files/db_connect.php");

if(isset($_SESSION['user_id'])) {
    header("Location: index.php");
}
$error = false;
if (isset($_POST['signup'])) {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);
    $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']); 
    if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
        $error = true;
        $uname_error = "Name must contain only alphabets and space";
    }
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
        $error = true;
        $email_error = "Please Enter Valid Email ID";
    }
    if(strlen($password) < 6) {
        $error = true;
        $password_error = "Password must be minimum of 6 characters";
    }
    if($password != $cpassword) {
        $error = true;
        $cpassword_error = "Password and Confirm Password doesn't match";
    }

    if (!$error) {
        if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
            $success_message = "Successfully Registered!";
        } else {
            $error_message = "Error in registering...Please try again later!";
        }
    }

}
?>



<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="registrationFormLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content" >
      <div class="modal-header">
        <h5 class="modal-title" id="registrationFormLabel">Register</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
        <div class="modal-body">


<!-- REGISTRATION FORM -->
<div class="container">
<div class="form-row">
<div class="col">
    <form onsubmit="return validateForm()" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
        <fieldset>
            <legend>Sign Up</legend>
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
                <span class="text-danger"><?php if (isset($uname_error)) echo $uname_error; ?></span>
            </div>                  
            <div class="form-group">
                <label for="name">Email</label>
                <input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
                <span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
            </div>
            <div class="form-group">
                <label for="name">Password</label>
                <input type="password" name="password" placeholder="Password" required class="form-control" />
                <span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
            </div>
            <div class="form-group">
                <label for="name">Confirm Password</label>
                <input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
                <span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
            </div>
            <div class="form-group text-center">
                <input id="modalSubmit" type="submit" name="signup" value="Sign Up" class="btn btn-primary" formnovalidate />
            </div>
        </fieldset>
    </form>
    <span class="text-success"><?php if (isset($success_message)) { echo $success_message; } ?></span>
    <span class="text-danger"><?php if (isset($error_message)) { echo $error_message; } ?></span>
</div><!-- / col -->
</div><!-- / form-row -->

<!-- already registered row -->
<div class="row">
<div class="col text-center">   
    Already Registered? <a href="login.php">Login Here</a>
</div>
</div>  <!-- / already registered row -->
</div><!-- / REGISTRATION FORM container-->

        </div><!-- / Modal body div -->
      </div>
  </div>
</div><!-- / Modal -->

My modal opens when the user clicks the button on index page and here is the JQuery code

$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myModal").modal();
    });
}); 
Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
PeterPan
  • 25
  • 9
  • try changing `required` to `required="yes"` – JamesBond Mar 21 '18 at 14:17
  • it still disappears. Probably would need to change to client side validation – PeterPan Mar 21 '18 at 14:23
  • The problem is the structure, when you insert a submit form if you keep the default behaviour the modal will close always, so change the input type submit in an input type button you can also keep type submit but must do an ajax call so a $.post(url) or a event.preventDefault to avoid the modal will close. –  Mar 21 '18 at 15:04
  • where's your `function validateForm() { ... }` code? – Taufik Nur Rahmanda Mar 21 '18 at 15:06

2 Answers2

0

Add below PHP script after end of document (/html) before script tag

<?php 
if ($error) {
    echo '<script>$("#myModal").modal("show");</script>';
} else {
    echo '<script>$("#myModal").modal("hide");</script>';
}
?>
user6016913
  • 181
  • 2
  • 10
  • Thanks! Nice and simple. That's what I needed. Being alone from of PC doesn't help. Power in the community – PeterPan Mar 21 '18 at 19:21
0

Invalid: You can stop the submit button from submitting if the inputs are invalid.

To stop submit use the code

$(':input[type="submit"]').prop('disabled', true);

To show modal

$("#myModal").modal('show');

To enable submit again, when modal is closed due to error, use the code (You will want to enable it again so the user can try again)

$("#myModal").on('hidden.bs.modal', function (e) {
        $(':input[type="submit"]').prop('disabled', false);
    });

For the validation I would do it this way (add a success variable):

if (!$error) {
    if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
        $success = 1;
    } else {
        $success = 2;
    }

And then call it like this:

<?php if($success == 1){ ?>
<script>
    $(document).ready(function() {
        $("#yoursuccessmodal").modal('show');
    });
</script> <?php } ?>

You can then choose to add a fade to it, or have the user click it away. The modal will then show AFTER the submition has been sent.

This better work, as I have used it this way in my project as well and it works like a charm for me.

  • Thank You. I haven't run your code but thanks for the response. Simple if statement from @user6016913 done the job. – PeterPan Mar 22 '18 at 03:37
  • OK I have tried your approach but I m having some trouble :( Any chance you can help? I ll submit my code later on as it has been a looooong night for me Thanks in advance – PeterPan Mar 23 '18 at 05:57
  • So to enable the submit button again I can use the php validation code and check for the success variable ? Also can you please explain the syntax a bit to me... I m still new :( what does the hidden.bs.modal do? I have manage to get the modal to shop up when button is clicked and disable the submit button but I m struggling a bit to enable the button when user fills all the fields. I ll try more after some sleep :) – PeterPan Mar 23 '18 at 06:45