0

So I tried making my own contact form and that kind of worked but I really wanted to add some cool features like telling users when they didn't fill in a required form and telling them when they submitted the form correctly. I got this code from this site. Whenever I click the submit button it takes me to my PHP file link and the page is blank! I want to be able to stay on the same page and have the success/error messages appear not to be redirected. Sorry, I'm a bit new to web development.

BOTH FILES ARE .PHP!!!

Here's the code:

<?php
    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
    $subject = $_POST['subject'];
        $from = 'Plugin Request Form'; 
        $to = 'theslimeslayer04@gmail.com'; 
        $subject = 'New Plugin Request';

        $body = "From: $name\n E-Mail: $email\n Subject: $subject\n Message:\n $message";

        // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (!$_POST['message']) {
            $errMessage = 'Please enter your message';
        }
    if(!$_POST['subject']) {
      $errSubject = 'Please enter a subject';
    }

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
    if (mail ($to, $subject, $body, $from)) {
        $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
    } else {
        $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
    }
}
    }
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="description" content="My very first website.">
  <meta name="author" content="Reprevise">
  <meta name="keywords" content="My development portfolio.">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Reprevise | Home</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <link rel="stylesheet" type="text/css" href="assets/css/layout.css">
  <link rel="stylesheet" type="text/css" href="assets/css/theme.css">

  <link rel="shortcut icon" href="assets/images/favicon.ico" type="image/x-icon">
  <link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">

</head>

<body>

  <nav class="nav" id="homelink">
    <div class="container">
      <div class="logo">
        <img class="sitelogo" src="assets/images/logo.jpg" alt="logo">
      </div>
      <ul class="menu">
        <li><a href="#homelink">Home</a></li>
        <li><a href="#aboutlink">About</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
    </div>
  </nav>

  <header>
    <div class="title-wrapper">
      <h1 class="header-title">reprevise's dev studio</h1>
    </div>
  </header>

  <div class="aboutsection" id="aboutlink">
    <div class="headingtitle-wrapper">
      <h1>About Reprevise</h1>
    </div>
    <div class="about-paragraph">
      <p style="text-align: left;">Benjamin, otherwise known as Benjamin has been a developer of all different types of programming languages for about 3 years now. He has knowledge of Lua, Java, HTML, CSS, JS, C#, and Python. Ben loves to make Minecraft plugins for all sorts of
        clients for free! Below is a contact form in which you can hit him up if you have a plugin request.</p>
    </div>
  </div>

  <div class="conform-container">
    <div id="contact">
      <div class="conform-heading-wrapper">
        <h1>Contact Form</h1>
        <h4>Send me plugin requests here.</h4>
      </div>
      <form class="form-horizontal" role="form" method="post" action="form-handler.php">
        <div class="form-group">
          <label for="name" class="col-sm-2 control-label">Name</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
            <?php echo "<p class='text-danger'>$errName</p>";?>
          </div>
        </div>
        <div class="form-group">
          <label for="email" class="col-sm-2 control-label">Email</label>
          <div class="col-sm-10">
            <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
            <?php echo "<p class='text-danger'>$errEmail</p>";?>
          </div>
        </div>
        <div class="form-group">
          <label for="subject" class="col-sm-2 control-label">Subject</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" id="subject" name="subject" placeholder="Really Important Plugin" value="<?php echo htmlspecialchars($_POST['subject']); ?>">
            <?php echo "<p class='text-danger'>$errSubject</p>";?>
          </div>
        </div>
        <div class="form-group">
          <label for="message" class="col-sm-2 control-label">Message</label>
          <div class="col-sm-10">
            <textarea class="form-control" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
            <?php echo "<p class='text-danger'>$errMessage</p>";?>
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-10 col-sm-offset-2">
            <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-10 col-sm-offset-2">
            <?php echo $result; ?>
          </div>
        </div>
      </form>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>

</html>
John Conde
  • 217,595
  • 99
  • 455
  • 496
Benjamin
  • 5,783
  • 4
  • 25
  • 49
  • At no point do you attempt to output anything after you process the form. All you do is put content in a variable but you never output it. – John Conde Dec 19 '18 at 02:02
  • It's echoed in the HTML file. – Benjamin Dec 19 '18 at 02:04
  • You are confused how this all works. PHP is executed on the server side.Once that page is loaded that content is generated and that's it. You need to use Ajax and Javascript to update that content after the page is loaded. You need to read [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – John Conde Dec 19 '18 at 02:04
  • what is in this page `form-handler.php` ? AKA the form action... – ArtisticPhoenix Dec 19 '18 at 02:08
  • @ArtisticPhoenix That contains the logic for handling the form and creating a response. But they are assuming the value of `$response` will show up after the form submission. They don't understand the HTTP lifecycle. – John Conde Dec 19 '18 at 02:09
  • `That contains the logic for handling the form and creating a response` As far as I know it could contain a 404. None of the code bits are named with file names. – ArtisticPhoenix Dec 19 '18 at 02:11
  • @ArtisticPhoenix It's the first code block in the question. You can see where they populate `$response` and in the next code block you can see where they expect it to magically appear. – John Conde Dec 19 '18 at 02:12
  • So can anybody recommend a good tutorial for creating a contact form in PHP? – Benjamin Dec 19 '18 at 02:18
  • I'm sure Google can. – yaakov Dec 19 '18 at 02:36
  • Just Google "how to make an ajax contact form" – yaakov Dec 19 '18 at 02:37

1 Answers1

0

The answer to your question is found inside of the PHP script in your post.

If there are no errors, send the email

That contact form is designed to send emails only. It's not designed to dump out an HTML response to the page.

However, you can add it easily at the bottom of the .PHP file. This example simply uses the basic php_include command, which loads another file. You could add standard HTML markup into that file.

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
    if (mail ($to, $subject, $body, $from)) {
        $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
    } else {
        $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
    }
} else {
   php_include('.../some/path/to/a/file.php');
}
    }
?>
...

But what you really want, is something like this. The idea is that you're not leaving the form, when the <input type="submit"> button is pressed...

<form class="form-horizontal" role="form" onSubmit="return false;">

Then you can use JavaScript to show people some...

cool features like telling users when they didn't fill in a required form and telling them when they submitted the form correctly

Wikipedia has a good overview of how AJAX technology works. Once you understand how Ajax engines work, then you may want to look into using jQuery.

The jQuery $.post() method is an easy way to send form data from a page over to the server using AJAX. Another simple example to use is $.get(). For a more advanced example, see the $.ajax() method. There is also a pretty comprehensive API of pre-built methods to peruse.

Hopefully, that answers your original question & points you into the right direction of learning how to start becoming an Ajax programmer. Good luck with your contact form! :)

Clomp
  • 3,168
  • 2
  • 23
  • 36