1

I have searched for all posible answers but i didn't find the right one. I have an html page where i want to show up the modal form. This form is in another page written in php. The modal is working and also it is the connection with the database. But when i click on the submit button and the information is not correct it redirect me to the php page. What a want is to stay in the modal and there appear that you need to fill the required field.

P.S. I am sorry if I am not too clear, it is my first post.

The html code (index.php):

<!DOCTYPE html>
<html lang="en" dir="ltr">
    
<head profile="http://www.w3.org/1999/xhtml/vocab">
    <link rel="shortcut icon" href="styles/icons/favicon.png" type="image/png" />
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>Hackaton | IBM Watson</title>
 <link type="text/css" rel="stylesheet" href="styles/style.css" />
    <link type="text/css" rel="stylesheet" href="styles/modal.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="all">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
   <!-- Modal -->
    <script type="text/javascript">
    <!--//--><![CDATA[//><!-- 
    $(document).ready(function(){
        $('.openPopup').on('click',function(){
        var dataURL = $(this).attr('data-href');
        $('.modal-body').load(dataURL,function(){
            $('#myModal').modal({show:true });
            });
        });
    });
    //--><!]]>
    </script>
    <!-- Smooth scroll-->
    
</head>
<body class="html front not-logged-in no-sidebars page-node parallax-active sff-7 slff-7 hff-7 pff-7 form-style-1 wide" >
<!-- There is more code here but not important for this-->

<a class="btn-primary btn openPopup" data-href="form_group.php"><span>Grupo</span></a>
                    <!-- Modal -->
                     <div class="modal fade" id="myModal" role="dialog">
                        <div class="modal-dialog" role="document">
                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-body">
        
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Also more code here-->
</body>
</html>

The php code (form_group.php):

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title>Formulario de Registro Grupo</title>
 <link rel="stylesheet" href="styles/form.css" />
    <link type="text/css" rel="stylesheet" href="styles/fonts/lato-font.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="all">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body class="body-form">

<?php 
//Variables for SQL
$servername = "localhost";
$username = "prueba";
$password = "";
$dbname = "";
//define variables and set to empty values
$error = false;
$nameErr = $emailErr = $phoneErr = $teamErr = $ideaErr = "";
$name = $email = $phone = $idea = $team = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
    $error = true;
  } else {
    $name = test_input($_POST["name"]);
    $error = false;
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed";
      $error = true;
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
    $error = true;
  } else {
    $email = test_input($_POST["email"]);
    $error = false;
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
      $error = true;
    }
  }
    
  if (empty($_POST["phone"])) {
    $phoneErr = "Phone is required";
    $error = true;
  } else {
    $phone = test_input($_POST["phone"]);
    $error = false;
    // check if phone number is valid
    if (!preg_match("/^[0-9+]+$/",$phone)) {
      $phoneErr = "Invalid phone number";
      $error = true;
    }
  }

  if (empty($_POST["idea"])) {
    $ideaErr = "Your idea is required";
    $error = true;
  } else {
    $idea = test_input($_POST["idea"]);
    $error = false;
  }
//Falta el checkbox
  if (empty($_POST["team"])) {
    $teamErr = "Team is required";
    $error = true;
  } else {
    $team = test_input($_POST["team"]);
    $error = false;
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if(isset($_POST['submit'])) {
    if(!$error){
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);

        //Check connection
        if ($conn->connect_error){
            die("Connection failed: " . $conn->connect_error);
        }
        // prepare and bind
        $stmt = $conn->prepare("INSERT INTO form_grup (name, email, phone, idea, team) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $name, $email, $phone, $idea, $team);

        $stmt->execute();
        $stmt->close();
        $conn->close();

        echo "<script>
            location.replace('index.php#participa')
            </script>";

    }
    else{
         echo "<script>
            </script>";
    }
}
?>
<form id="sign-form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <h3 class="header">Take part as a team</h3>  
       
  <label class="label-form" for="idea">Your idea <br>
        <input class="input-text" type="text" name="idea" value="<?php echo $idea;?>" />
     </label> <br>
     <label class="error"><?php echo $ideaErr;?></label>
  <br><br>

  <label class="label-form" for="team">Your team description <br>
        <input class="input-text" type="text" name="team" value="<?php echo $team;?>" />
     </label><br>
     <label class="error"><?php echo $teamErr;?></label>
  <br><br>
  
     <label class="label-form" for="name">Name <br>
        <input class="input-text" type="text" placeholder="Name" name="name" value="<?php echo $name;?>">
     </label><br>
     <label class="error"><?php echo $nameErr;?></label>
  <br><br>            
      
     <label class="label-form" for="email">E-mail <br>
        <input class="input-text" type="text" placeholder="E-mail" name="email" value="<?php echo $email;?>">
     </label><br>
     <label class="error"><?php echo $emailErr;?></label>
  <br><br>
   
  <label class="label-form" for="phone">Phone/WhatsApp <br>
        <input class="input-text" type="text" placeholder="+XXX XXXXXXXXX" name="phone" value="<?php echo $phone;?>"/>
     </label><br>
     <label class="error"><?php echo $phoneErr;?></label>
  <br><br>
 
     <input class="i-submit" type="submit" name="submit" value="Take part">  
</form>

<?php

?>
</body>
</html>

This is the modal: enter image description here

This is what happen after clik on submit without fill the fields: enter image description here

Clara
  • 13
  • 2
  • 5
    it will be good if you use `ajax` instead of reloading the page. – urfusion Feb 28 '18 at 13:46
  • Possible duplicate of [jQuery Ajax POST example with PHP](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Rotimi Feb 28 '18 at 14:23
  • Thanks! I'm new in this so that's why i don't know too much abouy ajax, js, etc... – Clara Mar 01 '18 at 10:57

2 Answers2

1

Take a look at preventDefault() function. It prevent your action to finish. Like :

$('button').click(() => {
    this.preventDefault();
});

will block the button default action.

Or you could just send the form as an ajax post or get request.

Like so :

$.post('index.php', { username: yourUsername }, (data) => {
    //here you have your server response.
});
Jeremy M.
  • 1,154
  • 1
  • 9
  • 29
  • 2
    This should maybe have been a comment. There's not enough explanation here as to why `preventDefault()` would help. – Lewis Feb 28 '18 at 13:52
  • it's a link. The link will tell 100% much better why it would work than me. – Jeremy M. Feb 28 '18 at 13:54
  • 4
    Please [avoid link only answers](http://meta.stackoverflow.com/tags/link-only-answers/info). Answers that are "barely more than a link to an external site” [may be deleted](http://stackoverflow.com/help/deleted-answers). – Funk Forty Niner Feb 28 '18 at 13:55
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Jay Blanchard Feb 28 '18 at 13:56
0

Start by saying that the code you posted I would write it from the beginning and some things are to be reviewed but to remedy your problem change a little bit javascript in index.php

<script type="text/javascript">
    $(document).ready(function() {
        $('.openPopup').on('click', function() {
            var dataURL = $(this).attr('data-href');
            // Load from form_group.php only the form for view using target #sign-form
            $('.modal-body').load(dataURL + ' #sign-form', function() {
                $('#myModal').modal({show: true});
            });
        });
    });

    // Rebind form submit interceptor after each ajax
    $(document).ajaxComplete(function() {
        $('#sign-form').submit(function() {
            // Need to use $.post() instead $.load() becouse your php code manage only $_POST
            $.post('form_group.php', $(this).serialize() + '&' + $.param({'submit': true}), function(response) {
                // Load from form_group.php only the new form view based on erros
                $('.modal-body').html($(response).filter('#sign-form'));
            });

            return false;
        });
    });
</script>

Pssss.....Your validation code wrote in PHP not work very well becouse not check togheter the required fields. In example when you compile only $_POST['idea'] field the form is validate becouse you check it for last.

Alberto Favaro
  • 1,824
  • 3
  • 21
  • 46
  • Thank you so much!! Now is working! You are right about validation, i didn't realise it, i will change it now. Thanks again. – Clara Mar 01 '18 at 10:56
  • Please give me the up vote and mark as correct answer XD. Good work. – Alberto Favaro Mar 01 '18 at 11:01
  • haha done, sorry. I gave you the vote but it said that i have less than 15 of reputation so it won't be display but it will be recorded XD – Clara Mar 01 '18 at 11:44