我正试图通过ajax编写一个提交联系人表单,但不知何故,我在这个过程中失败了,我无法理解,我尝试的每个组合都会返回它0
出于某种原因。
这是我的表格
<form name="sentMessage" id="contactForm" novalidate>
<div class="form-group wow fadeInUp">
<input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group wow fadeInUp">
<input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group wow fadeInUp">
<textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 wow fadeInUp">
<div id="success"></div>
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</form>
这是包含的ajax脚本。
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
console.log(name + email + message);
if (firstName.indexOf(\' \') >= 0) {
firstName = name.split(\' \').slice(0, -1).join(\' \');
}
var data = $form.serialize();
console.log(data);
$.ajax({
url: ajax_contact.ajaxurl,
dataType: \'json\',
action: \'ajax_contact\',
data: ajax_contact.data,
cache: false,
success: function(data) {
console.log(data);
if(data.status == "success") {
// Success message
$(\'#success\').html("<div class=\'alert alert-success\'>");
$(\'#success > .alert-success\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-success\').append("<strong>" + data.message + "</strong>");
$(\'#success > .alert-success\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
}
if(data.status == "error") {
// Error message
$(\'#success\').html("<div class=\'alert alert-danger\'>");
$(\'#success > .alert-danger\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-danger\').append("<strong>" + data.message + "</strong>");
$(\'#success > .alert-danger\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
}
},
error: function() {
// Fail message
$(\'#success\').html("<div class=\'alert alert-danger\'>");
$(\'#success > .alert-danger\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-danger\').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$(\'#success > .alert-danger\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
我正确地添加了函数。php
function ajax_contact() {
try {
if (empty($_POST[\'name\']) || empty($_POST[\'email\']) || empty($_POST[\'message\'])) {
throw new Exception(\'Bad form parameters. Check the markup to make sure you are naming the inputs correctly.\');
}
if (!is_email($_POST[\'email\'])) {
throw new Exception(\'Email address not formatted correctly.\');
}
$website_email = !empty(get_theme_option(\'contact_email\')) ? get_theme_option(\'contact_email\') : get_bloginfo(\'admin_email\');
$subject = \'Website Contact Form from: \'.$_POST[\'name\'];
$headers = \'From: \'.get_bloginfo(\'name\').\' Contact Form \' .$website_email;
$send_to = $website_email;
$subject = get_bloginfo(\'name\') . " Contact Form: " .$_POST[\'name\'];
$message = "You have received a new message from your website contact form.\\n\\n"."Here are the details:\\n\\nName: " . $_POST[\'name\'] . "\\n\\nEmail: " . $_POST[\'email\'] . "\\n\\nMessage:\\n". $_POST[\'message\'] . "";
if (wp_mail($send_to, $subject, $message, $headers)) {
echo json_encode(array(\'status\' => \'success\', \'message\' => \'Contact message sent.\'));
exit;
} else {
throw new Exception(\'Failed to send email. Check AJAX handler.\');
}
} catch (Exception $e) {
echo json_encode(array(\'status\' => \'error\', \'message\' => $e->getMessage()));
exit;
}
die();
}
add_action( \'wp_ajax_ajax_contact\', \'ajax_contact\' );
add_action( \'wp_ajax_nopriv_ajax_contact\', \'ajax_contact\' );
function ajax_contact_js() {
wp_localize_script(\'ajax-contact\', \'ajax_contact\', array(\'ajaxurl\' => admin_url(\'admin-ajax.php\')));
}
add_action(\'wp_enqueue_scripts\', \'ajax_contact_js\');
我还将需要的所有脚本放入单独函数的队列中,因此我没有收到任何错误,似乎所有内容都已包含并正确添加,但在函数中,它以某种方式失败,我总是得到响应0。
最合适的回答,由SO网友:lonerunner 整理而成
最后我让它像这样工作。
<form name="sentMessage" id="contactForm" method="post" action="<?php echo admin_url(\'admin-ajax.php\'); ?>" role="form" data-toggle="validator">
<div class="form-group wow fadeInUp">
<input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-error="Please enter your name.">
<div class="help-block with-errors text-danger"></div>
</div>
<div class="form-group wow fadeInUp">
<input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-error="Please enter your email address.">
<div class="help-block with-errors text-danger"></div>
</div>
<div class="form-group wow fadeInUp">
<textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-error="Please enter a message."></textarea>
<div class="help-block with-errors text-danger"></div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 wow fadeInUp">
<div id="success"></div>
<input type="hidden" name="action" value="ajax_contact" />
<?php wp_nonce_field( \'contact_nonce\', \'contact_nonce\' ); ?>
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</form>
正如你在我添加的表格上看到的
method
到
post
和
action
到
wordpress ajax url
我还向注册的操作挂钩和nonce字段添加了具有值的隐藏字段。
在javascript文件中,我改为
$(\'#contactForm\').on(\'submit\', function(e) {
e.preventDefault();
var $form = $(this);
$.post( $form.attr(\'action\'), $form.serialize(), \'json\')
.done(function( data ) {
var response = JSON.parse(data);
if(response.status == "success") {
// Success message
$(\'#success\').html("<div class=\'alert alert-success\'>");
$(\'#success > .alert-success\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-success\').append("<strong>" + response.message + "</strong>");
$(\'#success > .alert-success\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
} else if(response.status == "error") {
// Error message
$(\'#success\').html("<div class=\'alert alert-danger\'>");
$(\'#success > .alert-danger\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-danger\').append("<strong>" + response.message + "</strong>");
$(\'#success > .alert-danger\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
} else {
// Fail message
$(\'#success\').html("<div class=\'alert alert-danger\'>");
$(\'#success > .alert-danger\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-danger\').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$(\'#success > .alert-danger\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
}
})
.fail(function() {
// Fail message
$(\'#success\').html("<div class=\'alert alert-danger\'>");
$(\'#success > .alert-danger\').html("<button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>×").append("</button>");
$(\'#success > .alert-danger\').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$(\'#success > .alert-danger\').append(\'</div>\');
//clear all fields
$(\'#contactForm\').trigger("reset");
});
最重要的部分是
JSON.parse
函数和注册的挂钩。php文件保持不变,我添加的唯一内容是检查nonce字段。