AJAX form post returns 0

时间:2020-12-30 作者:whatifthis

我正在开发一个简单的插件,它显示了一个HTML表单,用户可以在其中输入一个用于查询外部API的关键字。我目前已经设置了表单和相关的jQuery,但是当传递到插件的PHP文件时,我得到的响应仅仅是0。此时,我只想得到除0以外的任何响应(请参见echo "Whyyyy" 零件)。我一直在浏览互联网,觉得自己已经尝试了所有建议,这让我觉得自己在哪里犯了错误。

任何帮助都将不胜感激。

这是插件的PHP:

defined(\'ABSPATH\') or die(\'Ah ah ah. You didn\\\'t say the magic word.\');

class News_search {

    // Load scripts upon class initiation
    public function __construct() {
        add_action(\'wp_enqueue_scripts\', array($this, \'enqueue_scripts\'));
        add_action(\'wp_ajax_get_news_callback\', \'get_news_callback\');
        add_action(\'wp_ajax_nopriv_get_news_callback\', \'get_news_callback\');
        add_shortcode(\'wp_news_search\', array($this, \'wp_news_search_form\'));
    }

    function enqueue_scripts() {
        // Enqueue CSS
        wp_enqueue_style(\'wp-news-search\', plugins_url(\'/css/wp-news-search.css\', __FILE__));
        // Enqueue and localize JS
        wp_enqueue_script(\'ajax-script\', plugins_url(\'/js/wp-news-search_query.js\', __FILE__), array(\'jquery\'), null, true);
        wp_localize_script(\'ajax-script\', \'ajax_object\',
            array(\'ajax_url\' => admin_url(\'admin-ajax.php\'),
                \'security\' => wp_create_nonce(\'my-string-shh\'),
            ));
    }

    // Handle AJAX request
    function get_news_callback() {
        check_ajax_referer(\'my-special-string\', \'security\');
        $keyword = isset($_POST[\'news-keyword\']) ? $_POST[\'news-keyword\'] : null;
        echo "Whyyyy";
        die();

    }

    public function wp_news_search_form() {
        $content .= \'<form id="wp-news-search__form">
                        <label>
                            <input type="text" name="news-keyword" placeholder="\' . __(\'Enter keywords\') . \'" id="news-keyword" required>
                        </label>
                        <button id="wp-news-search__submit">\' .
                         __(\'Search for news\', \'wp-news-search\') .
                       \'</button>
                    </form>\';
        return $content;
    }

}

new News_search();
这是JS文件:

(function ($) {

    $(document).ready(function () {
        $(\'#wp-news-search__form\').submit(function (event) {
            event.preventDefault();

            // const keyword = $(\'#query-input\').val();
            const values = $(this).serialize();


            if (values) {
                // send stuff to php
                console.log(values);
                const data = {
                    action: \'get_news_callback\',
                    status: \'enabled\',
                    security: ajax_object.security,
                    form_data: values
                }

                $.post(ajax_object.ajax_url, data, function(response) {
                    if (response) {
                        console.log(`Response is: ${response}`);
                    }
                })
                    .fail(() => { console.error(\'error\'); })
                    .always(() => { console.log(\'form submitted\') });
            }

        });


    });

})(jQuery);

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

你的ajax post可调用函数action“;get_news_callback"E;在类中不工作\\uu construct(),因为可以在类中使用简单的Wordpress操作。

在类中使用操作:

add\\u action(\'wp\\u ajax\\u get\\u news\\u callback\',array(\'this,\'get\\u news\\u callback\');add\\u action(\'wp\\u ajax\\u nopriv\\u get\\u news\\u callback\',array(\'this,\'get\\u news\\u callback\');

您的脚本也会更改,因此您可以使用下面的脚本获得ajax响应。

defined(\'ABSPATH\') or die(\'Ah ah ah. You didn\\\'t say the magic word.\');

class News_search {

// Load scripts upon class initiation
public function __construct() {
    add_action(\'wp_enqueue_scripts\', array($this, \'enqueue_scripts\'));
    add_action(\'wp_ajax_get_news_callback\', array($this, \'get_news_callback\'));
    add_action(\'wp_ajax_nopriv_get_news_callback\', array($this, \'get_news_callback\'));
    add_shortcode(\'wp_news_search\', array($this, \'wp_news_search_form\'));
}

function enqueue_scripts() {
    // Enqueue CSS
    wp_enqueue_style(\'wp-news-search\', plugins_url(\'/css/wp-news-search.css\', __FILE__));
    // Enqueue and localize JS
    wp_enqueue_script(\'ajax-script\', plugins_url(\'/js/wp-news-search_query.js\', __FILE__), array(\'jquery\'), null, true);
    wp_localize_script(\'ajax-script\', \'ajax_object\',
        array(\'ajax_url\' => admin_url(\'admin-ajax.php\'),
            \'security\' => wp_create_nonce(\'my-string-shh\'),
        ));
}

// Handle AJAX request
public function get_news_callback() {
    
    check_ajax_referer(\'my-string-shh\', \'security\');

    $keyword = isset($_POST[\'form_data\']) ? $_POST[\'form_data\'] : null;
    
    echo $keyword;
    
    die();

}



public function wp_news_search_form() {
    $content .= \'<form id="wp-news-search__form">
                    <label>
                        <input type="text" name="news-keyword" placeholder="\' . __(\'Enter keywords\') . \'" id="news-keyword" required>
                    </label>
                    <button id="wp-news-search__submit">\' .
                     __(\'Search for news\', \'wp-news-search\') .
                   \'</button>
                </form>\';
     return $content;
   }

 }

 new News_search();
你的Js

(function ($) {

$(document).ready(function () {
    $(\'#wp-news-search__form\').submit(function (event) {
        event.preventDefault();

        // const keyword = $(\'#query-input\').val();
        const values = $(this).serialize();


        if (values) {
            // send stuff to php
            console.log(values);
            const data = {
                action: \'get_news_callback\',
                status: \'enabled\',
                type: "POST",
                security: ajax_object.security,
                form_data: values 
            }

            $.post(ajax_object.ajax_url, data, function(response) {
                if (response) {
                    console.log(`Response is: ${response}`);
                }
            })
                .fail(() => { console.error(\'error\'); })
                .always(() => { console.log(\'form submitted\') });
        }

    });


   });

})(jQuery);

SO网友:Jacob Peattie

这个check_ajax_referer() 功能将die() 如果检查失败,这就是为什么在它之后看不到任何内容,而失败的原因是wp_create_nonce()check_ajax_referer() 不匹配。

这里您使用的是一个字符串,\'my-string-shh\':

\'security\' => wp_create_nonce(\'my-string-shh\'),
但这里你用的是另一个,\'my-special-string\':

check_ajax_referer(\'my-special-string\', \'security\');
这些需要匹配。