我试图用ajax写一个Wordpress的联系表格。我有成功的问题,因为jquery没有附加确认。
PHP功能
add_action('wp_ajax_submit_form', 'submit_form_callback');
add_action('wp_ajax_nopriv_submit_form', 'submit_form_callback');
function submit_form_callback(){
$params = array();
parse_str($_POST['data'], $params);
$name = sanitize_text_field (trim( $params['name_contact'] ) );
$email = sanitize_email( $params['email_contact'] );
$message = wp_kses_data( $params['message_contact'] );
$subject = __('e-mail from ', 'ddflatro' ).get_bloginfo( 'url' ) ;
$site_owners_email = get_bloginfo('admin_email');
if ($name=="") {
$error['name'] = __( 'Please enter your name', 'ddflatro' );
}
if ( !preg_match( "/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email ) ) {
$error['email'] = __( 'Please enter a valid email address', 'ddflatro' );
}
else
{
$mailcheck = spamcheck($email);
if ($mailcheck==FALSE) {
$error['email'] = __( 'Please enter a valid email address', 'ddflatro' );
}
}
if ($message== "") {
$error['message'] = __( 'Please leave a message', 'ddflatro' );
}
if (!$error) {
$success['success'] = __('Yeah', 'ddflatro' );
echo json_encode($success);
$headers[] = 'From: ' . $name . ' <' . $email . '>' . "\r\n";
$headers[] = 'Content-type: text/html' . "\r\n";
wp_mail( $site_owners_email, $subject, $message, $headers );
} # end if no error
else {
echo json_encode($error);
}
die(); // this is required to return a proper result
}
的jQuery
$( "#contact-ddf" ).submit(function( event ) {
event.preventDefault();
$('#response').empty();
var data = {
action: 'submit_form',
data: $( this ).serialize()
};
$.post(ajaxurl, data, function(response) {
console.log(response);
if(response.success){
$('#response').append(response.success);
}
alert( response );
if(response.name){
$('#response').append(response.name + "<br>");
}
if(response.email){
$('#response').append(response.email + "<br>");
}
if(response.message){
$('#response').append(response.message + "<br>");
}
if(response.subject){
$('#response').append(response.subject + "<br>");
}
},'json');
});
如果缺少姓名或电子邮件或消息jQuery附加通知,但发送电子邮件时没有任何事情发生。
答案 0 :(得分:0)
我发现没有拼写错误或奇怪的东西。您可以尝试像这样定义标题:
$ headers = array('Content-Type:text / html; charset = UTF-8');
注意: 邮件标题有问题看看这个: http://core.trac.wordpress.org/ticket/23578
RGDS, 弗洛里安
答案 1 :(得分:0)
请在此处添加一行,然后尝试:
$.post(ajaxurl, data, function(response) {
response = jQuery.parseJSON(response); // this line should add to parse json
console.log(response);