WordPress AJAX JSON成功返回不被识别

时间:2015-10-25 作者:Jacob Buller

我正在使用jQuery Ajax调用方法为一个网站制作一个联系表单,然后使用WordPress在admin Ajax中的构建。php提交表单值,通过wp\\U mail将其发送到电子邮件地址,如果成功,则通过json\\U编码发回数组。表单可以工作,电子邮件也可以发送,但之后不会发送成功数据,Ajax:success功能也不会启动。

这在其他网站上也起到了作用,我不知道为什么它在这个网站上不起作用。它发送电子邮件,只是我的jQuery方法没有成功回调。

这是我一直在用的东西。

jQuery

(document).ready(function($){

$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\\s]+$/i.test(value);
}, "Only alphabetical characters"); 

$.validator.addMethod("phoneNum", function(value, element) {
    return this.optional(element) || /^[0-9\\-\\s]+$/i.test(value);
}, "Phone number can only be number and dashes.");


$("#contact-form").validate({
    rules: {
        name: {
            required:true,
           lettersonly: true
        },
        email: {
            required: true,
            email: true
            },
        phone: {
            phoneNum: true,
            },
        message:  {
            required:true
        }
        },
     messages: {
            name:  {
                required: "Please enter your name.",
                lettersonly: "Needs to be letters, no numbers please."
            },
            email: {
                required: "Please enter your email adress.",
                email: "Please enter your valid email adress."
            },
            phone: {

            },
            message:{
                required: "Please enter a message.",
            }
          },

    submitHandler: function(form) {
    $(\'#contact-msg\').html(\'<p class="ajaxLoader">Sending Email...</p>\');

       $.ajax ({
            type: \'POST\',
            url:  ajax_object.ajax_url,
            data: $(\'#contact-form\').serialize(),
            dataType: \'json\',
            success: function(response) {
                        if (response.status == \'success\') {
                            $(\'#contact-form\')[0].reset();
                        }
                        $(\'#contact-msg\').html(response.errmessage);
                    }
                });

    }

});
});
功能。php

// CONTACT FORM SCRIPTS    
function contactform_add_script() {

wp_enqueue_script( \'contactform-script\', get_template_directory_uri().\'/assets/js/contact_me.js\', array(\'jquery\') , null, true);
wp_localize_script( \'contactform-script\', \'ajax_object\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );

}
add_action(\'wp_enqueue_scripts\', \'contactform_add_script\');


// CONTACT FORM PROCESSING 
 function ajax_contactform_action_callback() {
$error = \'\';
$status = \'error\';
if (empty($_POST[\'name\']) || empty($_POST[\'email\']) || empty($_POST[\'message\'])) {
    $error = \'All fields are required to enter.\';

    } else {
        $name = filter_var($_POST[\'name\'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
        $email = filter_var($_POST[\'email\'], FILTER_SANITIZE_EMAIL);
        $number = filter_var($_POST[\'phone\'], FILTER_SANITIZE_NUMBER_INT);
       // $treatments = filter_var($_POST[\'treatments\'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
        $subject = \'A message from St. Romain Interiors\\\'s contact form.\';
        $message .= PHP_EOL.\'Sender\\\'s name: \'.$name;
        $message .= PHP_EOL.\'Phone number: \'.$number;
        $message .= PHP_EOL.\'E-mail address: \'.$email;

        $message .= PHP_EOL.\'Message: \'.stripslashes($_POST[\'message\']);

        $sendmsg = "Thanks for the message! We will respond as soon as possible.";
        $to = \'[email protected]\'; // If you like change this email address
        // replace "[email protected]" with your real email address

        $header .= \'Reply-To: \'.$email.PHP_EOL;
        if ( wp_mail($to, $subject, $message, $header) ) {
            $status = \'success\';
            $error = $sendmsg;
        } else {
            $error = \'Some errors occurred.\';
        }
    }

$resp = array(\'status\' => $status, \'errmessage\' => $error);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
}
add_action( \'wp_ajax_contactform_action\', \'ajax_contactform_action_callback\' );
add_action( \'wp_ajax_nopriv_contactform_action\',      \'ajax_contactform_action_callback\' );
更新!

如果我用这个替换提交者,它会返回一句话,但现在电子邮件永远不会发送。。。

     submitHandler: function(form) {
    $(\'#contact-msg\').html(\'<p class="ajaxLoader">Sending Email...</p>\');

        $.ajax ({
            type: \'POST\',
            url:  ajax_object.ajax_url,
            data: { action: "contactform_action",
                   values: $(\'#contact-form\').serialize() },
            dataType: \'json\',
            success: function(response) {

                        $(\'#contact-msg\').html(\'<p>Thanks for the message!</p>\');
                    }
                });

    }
更新#2

我用第一篇文章中的原始函数替换了success函数,但保留了您建议的数据值,它做的是相同的老事情,发送电子邮件但不发送成功回调。在Mozilla Firebug上,我可以在响应标题面板中找到此信息。

X-Robots-Tag:   noindex
X-Powered-By:   PHP/5.6.14
x-frame-options:    SAMEORIGIN
x-content-type-options: nosniff
Transfer-Encoding:  chunked
Server: Apache
Pragma: no-cache
Expires:    Wed, 11 Jan 1984 05:00:00 GMT
Date:   Mon, 26 Oct 2015 06:13:54 GMT
Content-Type:   application/json
Cache-Control:  no-cache, must-revalidate, max-age=0
更新#3

以下是我在Firebug中看到的反应

<br />
<b>Notice</b>:  Undefined index: name in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>156</b><br />
<br />
<b>Notice</b>:  Undefined index: email in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>157</b><br />
<br />
<b>Notice</b>:  Undefined index: phone in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>158</b><br />
<br />
<b>Notice</b>:  Undefined variable: message in<b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>161</b><br />
<br />
<b>Notice</b>:  Undefined index: message in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>165</b><br />
<br />
<b>Notice</b>:  Undefined variable: header in <b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>171</b><br />
{"status":"success","errmessage":"Thanks for the message! We will respond as soon as possible."}

2 个回复
最合适的回答,由SO网友:Jacob Buller 整理而成

The answer was that debug was set to \'true\' in wp_config. 由于函数中存在变量,这导致Wordpress返回错误html。php是通过ajax分配的,但Wordpress debug将其报告为“未定义”。在提交表单内容时,我通过查看Firebug控制台选项卡上的返回信息发现了这一点。返回中填写了
和未定义的错误。这导致AJAX响应中断,无法激活AJAX回调。将wp\\u config debug设置为“false”修复了所有问题。

至少这是我的假设,如果我错了,请纠正我

SO网友:Eduardo Sánchez Hidalgo Urías

您没有为AJAX调用指定操作名称。在WordPress中,您必须给出一个动作名称,与您在wp\\u ajax\\u和wp\\u ajax\\u nopriv之后给出的名称相同_

在这种情况下,如果您更改数据,AJAX调用应该可以工作:在AJAX调用中,对于以下内容:

data: {action: "contactform_action", values: $(\'#contact-form\').serialize()}
然后使用$_POST["values"]; 在php函数中。

相关推荐

WordPress AJAX错误400向远程站点发送数据的错误请求

我正在使用发件人。net获取电子邮件订阅列表。这个网站给了我一些信息,可以将用户的电子邮件添加到订阅列表中。我想使用WordPress ajax来实现这一点。但它返回错误400错误请求。我的代码是:文件ajax新闻脚本。js公司: jQuery(document).ready(function($){ // Perform AJAX send news on form submit $(\'form#fnews\').on(\'submit\', funct