-1

I am trying to create a contact form on my website that will check all fields for input (turn red if empty) then submit the message to the database while remaining on the same page. Currently the data is being transmitted via PHP and bypassing the check altogether. I've read some posts about using Ajax to accomplish this but haven't been able to figure out how it would fit into my code and if the Ajax supplements the PHP or replaces it entirely.

function submitCheck() {
  let firstName = document.getElementById("contactfirstname").value;
  let lastName = document.getElementById("contactlastname").value;
  let emailAddress = document.getElementById("contactemail").value;
  let phoneNumber = document.getElementById("contactphone").value;
  let contactDescription = document.getElementById("contactdescription").value;
  let submitButton = document.getElementById("submitbutton").value;
  function firstNameCheck() {if(firstName ==''){
      document.getElementById("contactfirstnametitle").style.color = "rgba(231, 76, 60, 1)";
    }else {document.getElementById("contactfirstnametitle").style.color = "";}}
  function lastNameCheck() {if(lastName ==''){
      document.getElementById("contactlastnametitle").style.color = "rgba(231, 76, 60, 1)";
    }else {document.getElementById("contactlastnametitle").style.color ="";}}
  function emailCheck() {if(emailAddress ==''){
      document.getElementById("contactemailtitle").style.color = "rgba(231, 76, 60, 1)";
    }else {document.getElementById("contactemailtitle").style.color ="";}}
  function descriptionCheck() {if(contactDescription ==''){
      document.getElementById("contactdescriptiontitle").style.color = "rgba(231, 76, 60, 1)";
    }else {document.getElementById("contactdescriptiontitle").style.color ="";}}
function contactFormCheck() {
  firstNameCheck();
  lastNameCheck();
  emailCheck();
  descriptionCheck();
  }
  if(firstName !='' && lastName !='' && emailAddress !='' && contactDescription !=''){
    document.getElementById("contactform").style.display = "none";
    document.getElementById("submittedmessage").style.display = "block";
  }else {
    contactFormCheck();
  }
};
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "staci_lynn_photo";
$first_name = htmlspecialchars($_POST['first_name']);
$last_name = htmlspecialchars($_POST['last_name']);
$email_address = htmlspecialchars($_POST['email']);
$description = htmlspecialchars($_POST['description']);
$phone_number = htmlspecialchars($_POST['phone']);

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO user_message_table (first_name, last_name, email_address, description, phone_number)
VALUES ('$first_name', '$last_name', '$email_address', '$description', '$phone_number');";

if ($conn->query($sql) === TRUE) {
   echo "New record created successfully";
} else {
   echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
    <div id="contactme" class="contactme">
      <h1 class="title centered">Contact Me</h1>
      <div id="submittedmessage" class="radius centered">
        <h1>Submitted!</h1>
        <h2>I will review your message and get back to you as soon as possible.</h2>
      </div>
      <form id="form" action="./Resources/message.php" method="post">
      <div id ="contactform" class="contactform radius centered">
        <h2 id="contactfirstnametitle">*First Name</h2>
        <textarea id="contactfirstname" name="first_name" type="text" placeholder="First Name..."></textarea>
        <h2 id="contactlastnametitle">*Last Name</h2>
        <textarea id="contactlastname" name="last_name" type="text" placeholder="Last Name..."></textarea>
        <h2 id="contactemailtitle">*Email Address</h2>
        <textarea id="contactemail" name="email" type="text" placeholder="Email Address..."></textarea>
        <h2>Phone Number &#9743;</h2>
        <textarea id="contactphone" name="phone" type="text" placeholder="Phone Number..."></textarea>
        <H2 id="contactdescriptiontitle">*How Can I Help You?</h2>
        <textarea id="contactdescription" name="description" type="text" placeholder="Description..."></textarea>
        <h3 class="requirementsnote">* Indicates a required field</h3>
        <button id="submitbutton" class="submitbutton">Submit</button>
      </div>
    </form>
  </div>
  • 7
    You say that you haven't been able to figure out how to use ajax, but you're not showing any _attempt_ to use it here. Please take some time to learn from the resources that you've seen so that you can at least try _something_. After that, if you're having a specific problem with the code you've tried, we can help address the specific problem. – Patrick Q Jan 03 '19 at 20:17
  • https://stackoverflow.com/questions/12944329/add-onclick-function-to-a-submit-button. You need to call your JS in some way. That question shows it. Also, maybe use inputs instead of textareas everywhere. – nerdlyist Jan 03 '19 at 20:34

1 Answers1

0

After hours of trying, the solution was to remove the JavaScript field checks and here is the AJAX.

$(function() {

   // Get the form.
   var form = $('#form');

   // Get the messages div.
   var formMessages = $('#formMessages');

   // Set up an event listener for the contact form.
   $(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
     type: 'POST',
     url: $(form).attr('action'),
     data: formData
    })
    .done(function(response) {
     // Make sure that the formMessages div is hidden and the success message shows.
     $('#contactform').hide();
     $('#submittedmessage').show();

     // Set the message text.
     $(formMessages).text(response);

     // Clear the form.
     $('#first_name', '#last_name', '#phone_number', '#email', '#message', '#description').val('');
    })
    .fail(function(data) {
     // Make sure that the formMessages div has the 'error' class.
        $('#contactform').show();
     $('#submittedmessage').hide();

     // Set the message text.
     if (data.responseText !== '') {
      $(formMessages).text(data.responseText);
     } else {
      $(formMessages).text('Oops! An error occured and your message could not be sent.');
     }
    });

   });

  });