0

I was asked to make a website recently, but I'm not totally through my course yet. I'm learning as I make the website, which of course leads me to points along the way where I get stuck.

Normally I do my own research, and I have done so this time as well, but I'm still confused about PHP form submission.

Currently, I have a Contact US page where people can submit first and last name, email, phone, and their message. This so far is strictly HTML, CSS, and bootstrap, no PHP on this page.

I have gone through the PHP section of my course 2-3 times now, plus google searching, and I have also made a strictly PHP form in a separate .php file. I am using MAMP as my local server, and when I type in localhost:8888, the page comes up and the form submission works fine. here is my php code:

<!DOCTYPE HTML>
<html>
<head>
</head>

<body>

    <?php
// define variables and set to empty values
    $fnameErr = $emailErr = $messageErr = "";
    $fname = $lname = $email = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["fname"])) {
    $fnameErr = "Name is required";
  } else {        
        $fname = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
  $fnameErr = "Please enter a valid name"; 
} else

    $fname = test_input($_POST["fname"]);
  }

  $lname = test_input($_POST["lname"]);

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }

  $phone = test_input($_POST["phone"]);

 if (empty($_POST["message"])) {
    $messageErr = "Please enter a message";
  } else {
    $message = test_input($_POST["message"]);
  }

}

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

        * Required Field
        <br>
        <br>
        <form method="post" action="">

            <input type="text" name="fname" class="form-control input-lg" placeholder="First Name" value="<?php echo $fname;?>">
            <span class="error">* <?php echo $fnameErr;?></span>
            <br>


            <input type="text" name="lname" class="form-control input-lg" placeholder="Last Name" value="<?php echo $lname;?>">
            <br>

            <input type="text" name="email" class="form-control input-lg" placeholder="Email" value="<?php echo $email;?>">
            <span class="error">* <?php echo $emailErr;?></span>
            <br>

            <input type="text" name="phone" class="form-control input-lg" placeholder="Phone" value="<?php echo $phone;?>">
            <br>

            <textarea class="form-control" name="message" rows="8" placeholder="Message" value="<?php echo $message;?>"></textarea>
            <span class="error">* <?php echo $messageErr;?></span>
            <br>

            <button class="btn" type="submit" name="contact_submit">Submit</button>
        </form>

        <?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $message;
echo "<br>";
?>

</body>

</html>

Now what I'm trying to do is get this code to be triggered when the user hits the submit button on the html page. I want the user to stay on the page always. at the moment, when the user clicks the submit button, it redirects to the php page, where the form is pre-filled with php code, and none of the functionality works when you hit submit on that page. Here is the code from my HTML file:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>The Friendly Medium</title>

    <!-- Bootstrap -->
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/CStyles.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

    <div id="wrapper">

        <div id="content">

            <nav class="navbar navbar-fixed-top navbar-inverse">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>

                    </div>
                    <div class="collapse navbar-collapse" id="navbar-collapse">
                        <ul class="nav navbar-nav">

                            <a class="navbar-brand">
                                <img style="max-width:214px; 
                                    margin-top: -3px;
                                    margin-left:-514px;" src="img/Logo.png">
                            </a>

                            <li>
                                <a href="home.html">Home</a>
                            </li>
                            <li>
                                <a href="bookings.html">Bookings</a>
                            </li>
                            <li>
                                <a href="about.html">About</a>
                            </li>
                            <li class="active">
                                <a href="contact.html">Contact Us</a>
                            </li>

                        </ul>
                    </div>
                </div>
            </nav>

            <section class="contact">
                <div class="container"></div>
                <p>Please fill out the form below</p>
                <h5>* Reqired Field</h5>


                <div class="container">
                    <form action="php/get_post.php" method="post">


                        <input type="text" name="fname" class="form-control input-lg" placeholder="First Name*">

                        <input type="text" name="lname" class="form-control input-lg" placeholder="Last Name">

                        <input type="text" name="email" class="form-control input-lg" placeholder="Email*">

                        <input type="text" name="phone" class="form-control input-lg" placeholder="Phone">

                        <textarea class="form-control" name="message" rows="8" placeholder="Message*"></textarea>

                        <button class="btn" type="submit" name="contact_submit">Submit</button>


                    </form>

                </div>
            </section>


            <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <!-- Include all compiled plugins (below), or include individual files as needed -->
            <script src="bootstrap/js/bootstrap.min.js"></script>

            <div id="footer">2016</div>
        </div>
    </div>

</body>

</html>
Brandon
  • 1
  • 3
  • So you don't want the page to reload when you submit the form? You may have to look into Javascript's AJax in that case. I do think you are making your code much more complex than you need to though. – GrumpyCrouton Aug 30 '16 at 20:54

3 Answers3

0

As per your form action attribute your user gets redirected to php/get_post.php when he hits submit. I'm assuming that's the PHP code you entered? You are setting the variables like $phone at the top of the file, which means when the user goes to the page he gets those $_POST values printed on the same form because you have the same HTML there.

You need to wrap your PHP code so that you create your error checking AND if there is an error in the $_POST values, you show the form, otherwise you just handle registration and redirect the user back to frontpage where there are no value attributes in the form.

An even cleaner solution would be to return the $_POST values with the redirect and use the same form so you don't write redundant duplicate code.

if (empty($_POST["fname"])) {
    $fnameErr = "Name is required";
}

if(!empty($fnameErr)) {
    // Show HTML form where values are set
} else {
    // Handle registration and redirect user back
}

In my opinion you should always go with PHP first, then use JavaScript to create the toppings, because there are people out there who have JavaScript disabled.

Now to your actual question.

If you don't want the user to redirect anywhere meaning he doesn't reload or be redirected, I suggest familiarize yourself with JavaScript, specifically jQuery $.ajax which can handle asynchronous request.

A basic AJAX request (JavaSript) looks like this:

$('form').submit(function() {
  $.ajax({
    url: 'php/get_post.php',
    type: 'post'
    data: $(this).serialize(),
    success: function(response) {
        // Handle notificationsetc.
    }
  });
});
Rcls
  • 459
  • 4
  • 18
0

The inherent nature of a php form is to run a server-side script. If you want the user to come back to the contact page once the script is complete, you only need use a php redirect which is explained at length here.

Community
  • 1
  • 1
infamoustrey
  • 730
  • 8
  • 16
0

try this

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>The Friendly Medium</title>

<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="css/CStyles.css" rel="stylesheet">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

</head>

<body>

<div id="wrapper">

    <div id="content">

        <nav class="navbar navbar-fixed-top navbar-inverse">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>

                </div>
                <div class="collapse navbar-collapse" id="navbar-collapse">
                    <ul class="nav navbar-nav">

                        <a class="navbar-brand">
                            <img style="max-width:214px; 
                                margin-top: -3px;
                                margin-left:-514px;" src="img/Logo.png">
                        </a>

                        <li>
                            <a href="home.html">Home</a>
                        </li>
                        <li>
                            <a href="bookings.html">Bookings</a>
                        </li>
                        <li>
                            <a href="about.html">About</a>
                        </li>
                        <li class="active">
                            <a href="contact.html">Contact Us</a>
                        </li>

                    </ul>
                </div>
            </div>
        </nav>

        <section class="contact">
            <div class="container"></div>
            <p>Please fill out the form below</p>
            <h5>* Reqired Field</h5>


            <div class="container">
                                <?php
                                if(isset($_POST["contact_submit"])){
                                    $passed=FALSE;
                // define variables and set to empty values
                    $fnameErr = $emailErr = $messageErr = "";
                    $fname = $lname = $email = $message = "";

                if ($_SERVER["REQUEST_METHOD"] == "POST") {

                    if (empty($_POST["fname"])) {
                    $fnameErr = "Name is required";
                    $passed=FALSE;
                  } else {        
                        $fname = test_input($_POST["fname"]);
                if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
                  $fnameErr = "Please enter a valid name"; 
                  $passed=FALSE;
                } else

                    $fname = test_input($_POST["fname"]);
                    $passed=TRUE;
                  }

                  $lname = test_input($_POST["lname"]);

                  if (empty($_POST["email"])) {
                    $passed=FALSE;
                    $emailErr = "Email is required";
                  } else {
                    $email = test_input($_POST["email"]);
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $passed=FALSE;
                      $emailErr = "Invalid email format"; 
                    }else{
                        $passed=TRUE;
                    }
                  }

                  $phone = test_input($_POST["phone"]);

                 if (empty($_POST["message"])) {
                    $messageErr = "Please enter a message";
                    $passed=FALSE;
                  } else {
                    $passed=TRUE;
                    $message = test_input($_POST["message"]);
                  }

                }

                function test_input($data) {
                  $data = trim($data);
                  $data = stripslashes($data);
                  $data = htmlspecialchars($data);
                  return $data;
                }
                if($passed)
                {
                echo "<h2>Your Input:</h2>";
                echo $fname;
                echo "<br>";
                echo $lname;
                echo "<br>";
                echo $email;
                echo "<br>";
                echo $phone;
                echo "<br>";
                echo $message;
                echo "<br>";
                }
                }
                ?>
                <form action="" method="post">


                    <input type="text" name="fname" class="form-control input-lg" placeholder="First Name*"><span class="error">* <?php echo $fnameErr;?></span>

                    <input type="text" name="lname" class="form-control input-lg" placeholder="Last Name">

                    <input type="text" name="email" class="form-control input-lg" placeholder="Email*"><span class="error">* <?php echo $emailErr;?></span>

                    <input type="text" name="phone" class="form-control input-lg" placeholder="Phone">

                    <textarea class="form-control" name="message" rows="8" placeholder="Message*"></textarea><span class="error">* <?php echo $messageErr;?></span>

                    <button class="btn" type="submit" name="contact_submit">Submit</button>


                </form>

            </div>
        </section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="bootstrap/js/bootstrap.min.js"></script>

        <div id="footer">2016</div>
    </div>
</div>

</body>

</html>
Abhijit Jagtap
  • 2,740
  • 2
  • 29
  • 43
  • 1
    Thanks for the replies everybody. A lot of what you've posted is a bit over my head at the moment, but I'll try to implement what I learn from it and report back. – Brandon Aug 31 '16 at 17:23