嘿伙计们我有一个表格应该在不重新加载页面的情况下发送消息。我在这里使用了这个教程:http://www.elated.com/articles/slick-ajax-contact-form-jquery-php/并根据我的需要进行了调整。这是php:
<?php
session_start();
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "myemail@email.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );
// Read the form values and define variables
$success = false;
$senderName = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
$honeypot = $_POST['url'];
$code = $_POST['code'];
//if the honeypot is filled out, dont send the form
if (!empty($honeypot)){
$success = false;
}
// If all values exist and the code matches, send the email
else if ( $senderName && $senderEmail && $message && $code == $_SESSION['random_code'] ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
// Return an appropriate response to the browser
if ( isset($_POST["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
这是javascript:
function submitForm() {
var contactForm = $(this);
//submit the form to the PHP script via Ajax
$('#sendingMessage').fadeIn();
$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
// Prevent the default form submission occurring
return false;
}
function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();
if ( response == "success" ) {
// Form submitted successfully:
// 1. Display the success message
// 2. Clear the form fields
$('#successMessage').fadeIn().delay(5000).fadeOut();
$('#name').val( "" );
$('#email').val( "" );
$('#message').val( "" );
} else {
// Form submission failed: Display the failure message,
$('#failureMessage').fadeIn().delay(5000).fadeOut();
}
}
当用户点击发送按钮并且在检查完所有字段之后运行该功能。我认为它在php结束时翘起来,它说if(isset($ _ POST ['ajax']))因为我一直被重定向到html回退,好像我没有启用javascript(我做的是方式)。你可以在这里看到一个有效的例子:mattsandersdesign.com/test/contact2.html 提前谢谢!
答案 0 :(得分:0)
即使所有验证检查都通过,您也必须return false
。否则表格将提交。
你甚至还打电话给submitForm()
吗?
答案 1 :(得分:0)