$wpdb使用AJAX,但显示AJAX错误而不是成功

时间:2020-11-16 作者:Raashid Din

是否有人会指导此代码为何不起作用。甚至数据也会发生变化。这是我使用的ajax。

jQuery(document).ready(function($) {
    $(".ue_ajax_enabled").on(\'click\', function(event) {
        event.preventDefault();
        /* Act on the event */
        $.ajax({
            url:  ue_ajax.ajax_url,
            type: \'POST\',
            /*dataType: \'json\',*/
            data: {
                \'action\'    : \'ue_ajax_enabled\',
                \'new_username\'  : $("#new_username").val(),
                \'nonce\'     : $("#new_username_nonce_check").val(),
            },
            beforeSend: function () {
                $(".ue_ajax_enabled").text(ue_ajax.beforeMessage);
            },
            success: function (data) {
                console.log(\'Success\');
                console.log(data);
            },
            error: function (data) {
                console.log(\'Error\');
                console.log(data);
            }
        })
        
    });
});
这是我使用的ajax动作挂钩。

    add_action( "wp_ajax_ue_ajax_enabled", \'ue_ajax_enabled\' );
    
    function ue_ajax_enabled() {
    global $wpdb;

    $currentUser = wp_get_current_user();
    $user_id = $currentUser->ID;

    if (  is_user_logged_in() && wp_verify_nonce( $_REQUEST[\'nonce\'], \'new_username_nonce\' ) && ! empty($_REQUEST[\'new_username\'])) {

        // Get name of our users table
        $tableName = $wpdb->prefix . \'users\';

        if ( !username_exists( $_REQUEST[\'new_username\'] ) ) {
            // Stripslashes and trim any whitespace, also replace whitespace with underscore
            $newUsername = trim(str_replace(\' \', \'_\', stripslashes($_REQUEST[\'new_username\'])));
        } else {
            echo json_encode( array(\'username\' => \'Username exists, try any other\') );
            die();
        }

        // Data to change
        $dataToChange = array(\'user_login\' => $newUsername);

        // Where to Change
        $whereToChange = array(\'ID\' => $user_id); 

        // Change the data inside the table
        $result = $wpdb->update($tableName, $dataToChange, $whereToChange, array(\'%s\'), array(\'%d\'));


        if ($result) {
            echo json_encode( array(\'update\' => true) );
        } else {
            echo json_encode( array(\'update\' => false) );
            die();
        }

        if (ue_send_email_to_user()) {
            $subject = \'Username Changed Successfully ID:\' . $user_id;
            $message = "<p>You username has been successfully changed. Your new details are given below.</p>";
            $message .= "<strong>Previous Username:</strong><span>{$currentUser->user_login}</span>";
            $message .= "<strong>New Username</strong><span>{$newUsername}</span>";
            $from = "From: " . get_bloginfo(\'name\');

            wp_mail( array(ue_get_administrators_email(), $currentUser->email), $subject, $message, $from );
        }
    }
    die();
}
代码在控制台中抛出错误消息,而不是前面设置的ajax的成功消息。任何关于为什么会发生这种情况的线索。提前感谢

UPDATE: by commenting datatype the problem solves. But still it shows undefined when i access json.

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

代码中的问题很简单:如果要发送JSON响应,请确保它是有效的JSON响应,即发送正确的Content-Type 标头和正确的JSON编码正文。具有jQuery.ajax(), 虽然可以省略标题,但需要设置dataTypejson.

function my_ajax_callback1() {
    // Invalid JSON response.
    die();
}

function my_ajax_callback2() {
    // Good JSON response with a Content-Type header.

    header( \'Content-Type: application/json\' );
    echo json_encode( array( \'update\' => true ) );

    wp_die(); // die() works, but wp_die() is better
}
实际上,在回调中,您可以使用wp_send_json() 像这样:

function my_ajax_callback3() {
    wp_send_json( array( \'update\' => true ) );
    // No need to call wp_die(), die() or exit().
}
还有wp_send_json_success()wp_send_json_error(), 但在JS中,您需要使用data.data.<key> 而不是data.<key>, 除了data.success.

function my_ajax_callback4() {
    // ... your code

    // In your success( data ) JS, you\'d access the \'update\' value via data.data.update

    if ( $result ) {
        wp_send_json_success( array( \'update\' => true, \'msg\' => \'Success!\' ) );
    } else {
        wp_send_json_error( array( \'update\' => false, \'msg\' => \'Foo error\' ) );
    }
}
因此,请务必返回有效的响应数据,虽然不是必需的,但我建议您考虑creating a custom REST API endpoint 用于自定义AJAX操作,并将AJAX请求指向该API端点,该端点(默认情况下)始终返回JSON响应。

SO网友:Quang Hoang

我想您在提交未登录时忘记了WP中的ajax操作。因此,如果您想让它在前端为访问者和登录用户启动,可以执行以下操作:

add_action( \'wp_ajax_my_action\', \'my_action\' );
add_action( \'wp_ajax_nopriv_my_action\', \'my_action\' );
返回ajax后,必须使用die() 函数响应返回数据。

阅读更多:https://codex.wordpress.org/AJAX_in_Plugins