尝试提交数据而不离开当前页面

时间:2019-01-03 20:11:47

标签: javascript php html ajax forms

我正在尝试在我的网站上创建一个联系表单,该表单将检查所有字段的输入内容(如果为空,则显示红色),然后将消息提交到数据库,同时保留在同一页面上。当前,数据正在通过PHP传输并完全绕过检查。我已经阅读了一些有关使用Ajax完成此操作的文章,但无法弄清楚它如何适合我的代码,以及Ajax是否补充了PHP或完全取代了它。

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>

1 个答案:

答案 0 :(得分:0)

经过数小时的尝试,解决方案是删除JavaScript字段检查,这里是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.');
  			}
  		});

  	});

  });