成功登录后Wordpress AJAX登录不重定向

时间:2015-10-14 07:18:29

标签: ajax wordpress redirect login

我在WP站点中实现了基于AJAX的登录功能,如下所示:

functions.php

function ajax_login_init(){

    wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') ); 
    wp_enqueue_script('ajax-login-script');

    wp_localize_script( 'ajax-login-script', 'ajax_login_object', array( 
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'redirecturl' => home_url(),
        'loadingmessage' => __('Sending user info, please wait...')
    ));

    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}

// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_login_init');
}

function ajax_login(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-login-nonce', 'security' );

    // Nonce is checked, get the POST data and sign user on
    $info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;

    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
    } else {
        echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
    }

    die();
}

ajax-login-script.js

jQuery(document).ready(function() { 

    // Perform AJAX login on form submit
    jQuery('form#login_form').on('submit', function(e){
        jQuery('form#login_form p.login-status').show().text(ajax_login_object.loadingmessage);
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_login_object.ajaxurl,
            data: { 
                'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
                'username': jQuery('form#login_form #txtEmail').val(), 
                'password': jQuery('form#login_form #txtPassword').val(), 
                'security': jQuery('form#login_form #security').val() },
            success: function(data){
                jQuery('form#login_form p.login-status').text(data.message);
                if (data.loggedin == true){
                    document.location.href = ajax_login_object.redirecturl;
                }
            }
        });
        e.preventDefault();
    });

});

现在,当我在登录弹出窗口中输入错误的凭据时,它会成功显示等待消息,然后显示错误Wrong username or password.。但是当我使用正确的凭据并按下登录时,它会默默地登录我,但永远不会刷新页面(实际上它确实尝试在后台刷新页面,但由于它是一个ajax请求,我只能看到刷新console标签)。

我希望ajax刷新发送请求的当前页面。

我认为罪魁祸首可能是这个片段:

$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
            echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
        } else {
            echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
        }

当调用$user_signon = wp_signon( $info, false );时,它实际上会记录用户并重定向页面(在AJAX中),并且永远不会进一步执行代码。因此,我没有在我的AJAX成功函数中获取JSON编码数据(这是我实际尝试使用JavaScript重定向页面的地方)。

任何帮助都将受到高度赞赏。感谢

2 个答案:

答案 0 :(得分:2)

做到了另一种方式。使用wp_set_current_userwp_set_auth_cookiefunction ajax_login(){ // First check the nonce, if it fails the function will break check_ajax_referer( 'ajax-login-nonce', 'security' ); // Nonce is checked, get the POST data and sign user on $info = array(); $info['user_login'] = $_POST['email']; $info['user_password'] = $_POST['password']; $info['remember'] = true; $userdata = get_user_by('login', $info['user_login']); $result = wp_check_password($info['user_password'], $userdata->data->user_pass, $userdata->data->ID); if ( $result ) { auto_login( $userdata ); echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...'))); } else { echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.'))); } die(); } function auto_login( $user ) { if ( !is_user_logged_in() ) { $user_id = $user->data->ID; $user_login = $user->data->user_login; wp_set_current_user( $user_id, $user_login ); wp_set_auth_cookie( $user_id ); } } 函数来实现相同的目标。

defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }

答案 1 :(得分:0)

<form class="well form-inline" id="login">
    <div id="message"></div>
    <div id="loading" style="display:none;"></div>
    <div class="rowmargin">
        <h4>Login</h4>
    </div>
    <div class="rowmargin">
        <input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
        <input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
    </div>
    <a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>


jQuery(document).ready(function(){      
    jQuery('#loading').hide();
    jQuery("#loginButton").click(function() {   
        jQuery('#message').hide().html('');
        jQuery('#loading').hide();
        var input_data = jQuery('#login').serialize();
        var logUser = jQuery('#loginUsername').val();
        var logPass = jQuery('#loginPassword').val();

        if(logUser == '' && logPass != ''){ jQuery('#message').show().html('Your Username is empty!'); return false; }
        if(logPass == '' && logUser != ''){ jQuery('#message').show().html('Your Password is empty!'); return false; }
        if(logUser == '' && logPass == ''){ jQuery('#message').show().html('Your Username and Password is empty!'); return false; } 

        jQuery('#loading').show();
        jQuery.ajax({
            type: "POST",
            url: "<?php echo site_url('wp-login.php','login_post'); ?>",
            data: input_data,
            success: function(msg) {                                    
                // login success. redirect users to some page.
                jQuery(location).attr('href', '<?php echo home_url( '/thank-you/' ); ?>');

            },
            error: function(msg) {  
                // login error.                 
                jQuery('#message').show();
                jQuery('#message').html("<?php _e('Your login  is not correct. Please try again.'); ?>");
                jQuery('#loading').hide();
            }

        }); 
        return false;
    });
});