0
<?php
  $sendTo = "example@example.nl"; //Receiver mail
  $name = ""; //Sender's Name
  $email = ""; //Sender's email address
  $phone = ""; //Sender's mobile number
  $subject = ""; //Subject of form
  $message = ""; //Message of form
  $nameErr = "";
  $emailErr = "";
  $subjectErr = "";
  $messageErr = "";
  $succesMessage = "";

  //On submitting form, below function will execute
  if (isset($_POST['submit'])) {
    //Check if name is not empty
    if (empty($_POST['name'])) {
      $nameErr = "Name is required.";
    } else {
      $name = test_input($_POST['name']);
      //Check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
        $nameErr = "Only letters and whitespace allowed.";
      }
    }

    //Check if email is not empty
    if (empty($_POST['email'])) {
      $emailErr = "Email is required.";
    } else {
      $email = test_input($_POST['email']);
      //Check if email format is correct
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format.";
      }
    }

    //Phone
    if (empty($_POST['phone'])) {
      $phone = "Phonenumber not submitted.";
    } else {
      $phone = test_input($_POST['phone']);
    }

    //Subject
    if (empty($_POST['subject'])) {
      $subjectErr = "Subject is required.";
    } else {
      $subject = test_input($_POST['subject']);
     }

    //Message
    if (empty($_POST['message'])) {
      $messageErr = "Message is required.";
    } else {
      $message = test_input($_POST['message']);
    }

    if( !($name=='') && !($email=='') && !($subject=='') &&!($message=='') ) {
      $emailSubject = "New form submission";
      $header= "You have received a new e-mail from " .$name;
      $txt = $subject. "\n\n" .$message. "\n\n" . "Contact Details" ."\n". "Name: " .$name. "\n" . "Email: " .$email. "\n" . "Phone: " . $phone;

      /* Send the message using mail() function */
      if(mail($sendTo, $emailSubject, $txt, $header)) {
        $successMessage = "Message sent successfully. I will contact you shortly.";
        } else {
        $emailErr = "Invalid Email";
      }
    }
}

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

So I have this code standing above all html, the code works fine! But I do not want the page to reload and start at the top of the page. I want it to stay at the bottom of the page, because that's where contact form is located. How do I fix this?

I have read a bit fixing this with JavaScript issues, but I don't get it clear for myself to change my own code.

Html here:
<div class="form-container"> <form class="ccform" id="ccform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"> <span class="error"><?php echo $nameErr;?></span> <div class="ccfield"> <span class="ccform-icon"><i class="fa fa-user"></i></span> <input type="text" class="ccform-field" placeholder="*Full Name" name="name"> </div> <span class="error"><?php echo $emailErr;?></span> <div class="ccfield"> <span class="ccform-icon"><i class="fa fa-envelope"></i></span> <input type="email" class="ccform-field" placeholder="*Email" name="email"> </div> <div class="ccfield"> <span class="ccform-icon"><i class="fa fa-mobile-phone"></i></span> <input type="text" class="ccform-field" placeholder="Phonenumber" name="phone"> </div> <span class="error"><?php echo $subjectErr;?></span> <div class="ccfield"> <span class="ccform-icon"><i class="fa fa-info"></i></span> <input type="text" class="ccform-field" placeholder="*Subject" name="subject"> </div> <span class="error"><?php echo $messageErr;?></span> <div class="ccfield msgfield"> <span class="ccform-icon"><i class="fa fa-comment"></i></span> <textarea class="ccform-field" name="message" rows="8" placeholder="*Message"></textarea> </div> <div class="ccfield btnfield"> <input class="ccbtn" id="ccbtn" type="submit" value="Submit" name="submit"> </div> </form> <span class="error"><?php echo $succesMessage;?></span> </div>

Connor
  • 33
  • 4
  • thats how submitting a form works, its a whole new http request. –  May 08 '18 at 21:59
  • is this code on the same page as your form or on a different page? – JeanPaul98 May 08 '18 at 22:00
  • 2
    sdie note: your `mail()` function is wrong, the arguments are in the wrong order. Also millions of (legit) names will fail your regular expression check. –  May 08 '18 at 22:02
  • Welcome to StackOverflow. As folks have pointed out, submit causes a page reload. So, you can't solve your issue by causing php code to run (again) because the php code runs on the server. Instead, you'll need to use javascript code to run on the client. But this is not the place to get a beginner's tutorial on javascript. I suggest you search the web for `php javascript tutorial` and start with very simple examples and work your way up to solving your problem here. – Jeff Learman May 08 '18 at 23:34

1 Answers1

1

I think what you want is submitting a form using Ajax. This is your original code:

<?php

  // .....

  //On submitting form, below function will execute
  if (isset($_POST['submit'])) {

      // ..... 

      // After processing your form data, you have to output your result here. For example:
      echo $message;

      // then exit php script, so that it will not generate HTML below
      exit;
  }
?>

Your HTML should have a form looks like this:

<form id="myForm" method="post" action="contact.php">
    // ......
    <button id="btSubmit" name="submit">Submit</button>
</form>

To not refresh a page you must use Ajax, here I use jQuery:

<script>
    $(function() {
         $('#btSubmit').click(function() {
              var method = $('#myForm').attr('method');
              var action = $('#myForm').attr('action');
              $.ajax({
                  url: action, 
                  method: method,
                  data: $('#myForm').serialize();
                  success: function(data) { 
                       // your response data
                  }
              });
         });
    });        
</script>
Hope
  • 97
  • 1
  • 9
  • Okey I have a few more questions. My form must only have an id, not a method nor an action? In my form I use an input field as button, does that matter? I'm new to AJAX, so what do I need to put in my URL if the php is in the same file? And what do I need to put as response data? Thanx anyway! – Connor May 09 '18 at 11:10
  • You can still use any attribute you want, but the the $.ajax will not know those attributes so you have to read them manually and add to $.ajax options. For example, you have a form `
    `, then inside click function you can read the attribute values: `$('#myForm').attr('method')` and `$('#myForm').attr('action')` see modified code above. For input field as button see [https://stackoverflow.com/questions/469059/button-vs-input-type-button-which-to-use]. The response data is from `echo $message`.
    – Hope May 09 '18 at 13:48
  • Alright thanx Darith! But the last thing I don't get is the response data. What do I have to put there if you look at my php code? You are already a hero for helping me out man! – Connor May 09 '18 at 21:40
  • It doesn't work for me, it still sends me to the other php page. – Connor May 21 '18 at 15:39