在div中显示文本而不重新加载页面

时间:2014-10-08 12:44:35

标签: javascript php html email

在下面的代码中,我有一个联系表单,并且在该表单中有一个电子邮件验证脚本。作为验证的结果,我希望错误消息显示在div被叫确认中,而无需重新加载页面。此外,如果电子邮件有效,邮件将被发送,我希望谢谢您的邮件显示在同一div确认中。问题是如何防止重新加载页面并在确认div中显示错误消息或感谢消息?

<html>
<body>
<?php
function spamcheck($field) {
  // Sanitize e-mail address
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  // Validate e-mail address
  if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>

<?php
if (!isset($_POST["submit"])) {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Submit Feedback"><br>
  <div id="confirmation" style="display:none" align="center"></div>
  </form>
  <?php 
} else {  // the user has submitted the form
  // Check if the "from" input field is filled out
  if (isset($_POST["from"])) {
    // Check if "from" email address is valid
    $mailcheck = spamcheck($_POST["from"]);
    if ($mailcheck==FALSE) {
      echo"
      <script>
        document.getElementById('confirmation').text ='invalid email';
      </script>";
    } else {
      $from = $_POST["from"]; // sender
      $subject = $_POST["subject"];
      $message = $_POST["message"];
      // message lines should not exceed 70 characters (PHP rule), so wrap it
      $message = wordwrap($message, 70);
      // send mail
      mail("nawe11@gmail.com",$subject,$message,"From: $from\n");
      echo"
      <script>
        document.getElementById('confirmation').text ='Thank you';
      </script>";
    }
  }
}
?>
</body>
</html>

由于

2 个答案:

答案 0 :(得分:1)

<input type="text" name="from" id ="from">

致电示例:

var request = $.ajax({
  url: "file.php",
  type: "POST",
  data: { email : $('#from').val() }
});

request.done(function( msg ) {
  //handle HTML
});

request.fail(function( jqXHR, textStatus ) {
  //Handle problem at server side
});

PHP Side

<?php

$email = $_POST["email"]

function spamcheck($field) {
  // Sanitize e-mail address
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  // Validate e-mail address
  if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
    return 'valid';
  } else {
    return 'no_valid';
  }
}

echo spamcheck($email);

答案 1 :(得分:0)

使用只是PHP ,你无法做到这一点。

您所看到的通常称为AJAX,并使用客户端语言(Javascript) 它非常普遍,并在互联网上广泛使用。您可以通过在Google上搜索ajax来找到许多示例和可投放生产的脚本。

此处有更多信息:http://www.w3schools.com/ajax/

相关问题