在WordPress网站上发送AJAX请求时出现403错误

时间:2021-05-05 作者:matthias screed

我必须创建一个指定的表单,将数据注册到数据库中,并在不刷新页面的情况下发送邮件

所以我创建了一个脚本。js文件:

    (function ($) {
    $(document).ready(function () {

        jQuery(\'form[name="form_result"]\').on(\'submit\', function() {
            var form_data = jQuery(this).serializeArray();
            console.log(\'hello\');
            form_data.push({"name" : "security", "value" : ajax_nonce });
            console.log(form_data);
            // Here is the ajax petition
            jQuery.ajax({
                url : ajax_url,
                type : \'post\',
                data : form_data,
                success : function( response ) {
                    // You can craft something here to handle the message return
                    alert(response);
                },
                fail : function( err ) {
                    alert("there was an error: " + err );
                }
            });
            // This return prevents the submit event to refresh the page.
            return false;
        });    
      });
})(jQuery);
在我的功能中。我声明的php文件如下:

function javascript_variables(){ ?>
    <script type="text/javascript">
        var ajax_url = \'<?php echo admin_url( "admin-ajax.php" ); ?>\';
        var ajax_nonce = \'<?php echo wp_create_nonce( "secure_nonce_name" ); ?>\';
    </script><?php
}
add_action ( \'wp_head\', \'javascript_variables\' );


//AJAX REQUEST
function twentytwentychild_asset() {
    // ...
    wp_enqueue_script(\'jquery\');

    // Charger notre script
    wp_enqueue_script(
        \'twentytwentychild\',
        get_stylesheet_directory_uri(). \'/assets/js/script.js\', 
        array(\'jquery\'),
        \'1.0\', true
    );

    // Envoyer une variable de PHP à JS proprement
    wp_localize_script(\'twentytwentychild\', \'ajaxurl\', admin_url(\'admin-ajax.php\'));
}
add_action(\'wp_enqueue_scripts\', \'twentytwentychild_asset\');


add_action(\'wp_ajax_send_form\', \'send_form\'); // This is for authenticated users
add_action(\'wp_ajax_nopriv_send_form\', \'send_form\');

function send_form(){
    // This is a secure process to validate if this request comes from a valid source.
    check_ajax_referer( \'secure-nonce-name\', \'security\' );
 
    /**
     * First we make some validations, 
     * I think you are able to put better validations and sanitizations. =)
     */
     
    if ( empty( $_POST["name"] ) ) {
        echo "Insert your name please";
        wp_die();
    }
 
    if ( ! filter_var( $_POST["email"], FILTER_VALIDATE_EMAIL ) ) {
        echo \'Insert your email please\';
        wp_die();
    }
 
    if ( empty( $_POST["fcPhone"] ) ) {
        echo "Insert your phone please";
        wp_die();
    }

    $to = \'[email protected]\';

    $subject = \'Un potentiel consultant viens de faire une simulation!\';

    $body  = \'From: \' . $_POST[\'name\'] . \'\\n\';
    $body .= \'Email: \' . $_POST[\'email\'] . \'\\n\';
    $body .= \'Message: \' . $_POST[\'fcPhone\'] . \'\\n\';

    $headers = array(\'Content-Type: text/html; charset=UTF-8\');

    wp_mail( $to, $subject, $body, $headers );

    echo \'Done!\';
    wp_die();
     
}
我的模板页面这是一个简单的表单:

<form action="" method="post" name="form_result">
    <div id="simulation_form">
        <div style="margin-bottom: 2rem; display: flex;">
            <div class="vc_col-sm-4">
                <div class="simulation_form_q">Votre name:*</div>
                <div class="simulation_form_r">
                    <input type="text" id="name" name="name" required>
                </div>
            </div>
            <div class="vc_col-sm-8">
                <div class="simulation_form_q">Votre email:*</div>
                <div class="simulation_form_r">
                    <input type="email" name="email" id="email" required>
                </div>
            </div>
            <div class="vc_col-sm-8">
                <div class="simulation_form_q">Votre numero de telephone:*</div>
                <div class="simulation_form_r">
                    <input type="text" name="fcPhone" id="telephone" required>
                </div>
            </div>
        </div>

        <input type="hidden" name="action" value="send_form" style="display: none; visibility: hidden; opacity: 0;"/>
        <div class="simulation_form_btn">
            <input type="submit" value="calculez vos revenus">
        </div>
    </div>
</form>
但是当我发送Ajax请求时,我禁止了403错误,我不知道为什么我会清除缓存和cookie,我使用控制台日志调试Ajax请求并发送所有数据,但我仍然存在403错误,我不知道如何解决它

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

Short answer — how can you solve the problem: 当你打电话的时候check_ajax_referer(), 使用secure_nonce_name 作为第一个参数,即。check_ajax_referer( \'secure_nonce_name\', \'security\' ).

较长的答案

的第一个参数(即nonce操作)check_ajax_referer() 需要匹配的第一个参数wp_create_nonce(), 但在你的代码中,它们是secure-nonce-namesecure_nonce_name 因此,这将导致错误403,其基本意思是;无效的nonce;。

因此,请确保名称相等或nonce操作正确,例如使用secure_nonce_name 具有上述两种功能:

// In the script in javascript_variables():
var ajax_nonce = \'<?php echo wp_create_nonce( "secure_nonce_name" ); ?>\';

// Then in the AJAX callback (send_form()):
check_ajax_referer( \'secure_nonce_name\', \'security\' );

其他注意事项您应该考虑使用REST API 这与admin-ajax.php, 在处理请求时遇到错误时,提供更好、人性化的消息

SO网友:Rajilesh Panoli

check_ajax_referer( \'secure-nonce-name\', \'security\' );
请在代码上方尝试此操作

check_ajax_referer( $_POST[\'security\'], \'secure_nonce_name\' );

相关推荐

JQuery Datepicker在与日历交互之前显示错误的语言

在使用Woody Snippets插件编写为PHP代码段的完全自定义页面中,我需要使用jQuery日期选择器来选择日期。我正确地导入了必要的文件,并正确地调用和设置了日期选择器。昨天,我将日期选择器连接到一个隐藏的输入字段,这样当我单击一个图标时,日历就会浮动到位,一切都很好,即使是本地化,尽管我没有采取任何措施来本地化日历(导入i18n文件等)。。。今天,我不得不稍微改变一下页面的布局,所以我必须从头开始(内联)显示日历。根据demo 页面中,为了将日期选择器内联,只需将其附加到div而不是输入字段。d