如何在不刷新当前页面的情况下提交表单?

时间:2013-07-10 00:50:08

标签: html jquery form-submit php

我有一个相当基本的电子邮件表格

<form name="contactform" method="post" action="send_email.php" id="email_form">
  <div class="ContactHeaders">Name</div>
  <input type="text" name="Name" class="ContactBoxes" id="name"/><br/><br/>
  <div class="ContactHeaders">Email</div>
  <input type="email" name="Email" class="ContactBoxes"/><br/><br/>
  <div class="ContactHeaders">Message</div>
  <div style="width:100%">
    <textarea name="Message" maxlength="1000"></textarea><br/>
  </div>
  <div style="width: 100%">
    <input type="submit" class="Submitbtn" value="Submit">
  </div>
</form>

这是'send_email.php'

<?php
ob_start();
include 'navbar.php';
ob_end_clean();

if(isset($_POST['Email'])) {

  //declare variables
  $Name = $_POST['Name'];
  $Email = $_POST['Email'];
  $Message = $_POST['Message'];
  $complete = 0;
  $email_to = "someone@example.com";
  $email_subject = "Website Contact";

  //check all forms are filled in correctly

  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(preg_match($email_exp,$Email)) {
     $complete++;
     }
  $string_exp = "/^[A-Za-z .'-]+$/";
  if(preg_match($string_exp,$Name)) {
     $complete++;
     }
  if(strlen($Message) > 20) {
     $complete++; 
     } 
  //send email if $complete = 4
  if ($complete == 3){
      if (get_magic_quotes_gpc()) {
          $Message = stripslashes($Message);
      }
  $Message =  $Message . "\n\n" . "From " . $Name;
  $headers = 'From: '.$Email."\r\n".
 'Reply-To: '.$Email."\r\n" .
 'X-Mailer: PHP/' . phpversion();
 @mail($email_to, $email_subject, $Message, $headers);
 echo '<script>
     alert("Thank you for contacting me. I will be in touch shortly");
     top.location="index.php";
     </script>';
 }
 else {
     echo '<script>
             alert("The form you submitted is invalid. Please ensure the following: \n  You have provided a valid email address. \n  Your phone number is entered correctly. \n  The message box contains at least 20 characters.")
             history.go(-1)
          </script>';
    }
}

?>

所以我的问题是,当表单提交到php文件时,浏览器加载php文件,运行代码并返回结果(这不是一个问题,但它是我不想要的东西)然后它到java显示警报并返回一个(在我的代码中)。有没有办法让它在后台运行代码,所以表单运行PHP文件,而不必去它(如果这是有道理的),并在同一窗口中返回结果。我显然环顾四周,发现了很多关于AJAX的东西,但我并没有真正理解它,也无法让它为我工作。

执行此操作的原因有点复杂,但只要用户友好性适用于我的网站,以及看起来更干净(进入空白页面并显示警报看起来不太好)会使事情变得更加容易)。

提前感谢您提供给我的任何帮助:)

1 个答案:

答案 0 :(得分:0)

$('.Submitbtn').click(function(e) {
    e.preventDefault();
    // do some form validation here
    if form is valid { // from validation above
        var formData = $('#email_form').serialize();
        $.post('send_email.php',{data:formData});
    } else {
        alert('Form no good - fix it!');
        return false;
    }
});

这是你可以开始的东西。这是非常基础的,但为开始您的AJAX冒险提供了必要的基础。

50 Excellent AJAX Tutorials