注销并重定向 WordPress 用户 ID,无需刷新页面

问题描述 投票:0回答:1

我正在开发一个在按钮 $('.disconnect-classroom-button') 上触发的功能,当单击时,我注销该组内的所有成员,并且注销已成功完成(但用户必须单击或刷新页面才能即使我使用ajax也生效),这不是我想要的结果: 这是 php 回调函数:

// PHP function to send students_ids
function send_students_ids() {
    if (isset($_POST['payload']) && $_POST['payload'] == 'disconnect_classroom') {
        // Verify nonce
        check_ajax_referer('kwf_nonce', 'security');

        $group_type = bp_groups_get_group_type(bp_get_current_group_id());

        $students_ids = array();

        $group_members = groups_get_group_members(array(
            'group_id'            => bp_get_current_group_id(),
            'exclude_admins_mods' => true,
            'exclude_banned'      => true,
            'exclude'             => false,
            'group_role'          => array('member'),
            'search_terms'        => false,
        ));

        foreach ($group_members['members'] as $member) {
            $students_ids[] = $member->ID;
        }

        // Send students_ids to the JavaScript function
        wp_send_json_success(array('students_ids' => $students_ids));
    }
}

// Add the custom action hook to the wp_ajax_ hook
add_action('wp_ajax_send_students_ids', 'send_students_ids');

// PHP function to process logout using students_ids
function kwf_ajax_logout_group() {

    if (isset($_POST['payload']) && $_POST['payload'] == 'disconnect_classroom') {
        // Verify nonce
        check_ajax_referer('kwf_nonce', 'security');

        // Get the user IDs from the POST data
        $user_ids = $_POST['user_ids'];

        // Loop through the user IDs and log them out
        foreach ($user_ids as $user_id) {

            if (is_user_logged_in($user_id)) {
                // Get all sessions for the user with ID $user_id
                $sessions = WP_Session_Tokens::get_instance($user_id);
        
                // We have got the sessions, destroy them all!
                $sessions->destroy_all();
            }

        }

        // Send a success response
        wp_send_json_success(array(
            'message' => 'You will be logged out.',
            'user_ids' => $user_ids,
            'redirect_url' => home_url(), // Set the redirection URL
        ));


        // Redirect to the homepage after logging out
        
       // exit; 
    }
}

这是 ajax 中的事件处理程序: (仅对单组页面入队):

if(function_exists('bp_is_groups_component') && bp_is_groups_component()) { // single group
 wp_enqueue_script( 'kwf-bp-groups-js', KWF_JS_PATH . 'bp-groups.js', array( 'jquery' ), KWF_THEME_VERSION, true );}
    $('.disconnect-classroom-button').hover(
        function () {
            // Hover in: Change the icon to bb-icon-file-export with ease-in-out transition
            $(this).find('i').removeClass('bb-icon-file-import').addClass('bb-icon-file-export').css('transition', 'all 0.3s ease-in-out');
        },
        function () {
            // Hover out: Change the icon back to bb-icon-file-import with ease-in-out transition
            $(this).find('i').removeClass('bb-icon-file-export').addClass('bb-icon-file-import').css('transition', 'all 0.3s ease-in-out');
        }
    ).on('click', function (e) {
        e.preventDefault();
        var button = $(this);
        var nonce = $(this).data('security');
    
        NProgress.start();
        NProgress.set(0.4);
    
        // Increment 
        var interval = setInterval(function () {
            NProgress.inc();
        }, 1000);
    
        // Step 1: Send Member IDs
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: ajaxurl,
            data: {
                action: 'send_students_ids',
                payload: 'disconnect_classroom',
                security: nonce,
                send_members: true, // Add a flag to indicate sending member IDs
            },
            success: function (response) {
                // Check if sending member IDs was successful
                if (response.success) {
                    var memberIds = response.data.students_ids;
    
                    // Step 2: Process Logout
                    $.ajax({
                        type: 'post',
                        dataType: 'json',
                        url: ajaxurl,
                        headers: {
                            pragma: "no-cache",
                            "cache-control": "no-cache"
                        },
                        data: {
                            action: 'kwf_ajax_logout_group',
                            payload: 'disconnect_classroom',
                            security: nonce,
                            user_ids: memberIds, // Include the member IDs for logout
                        },
                        success: function (logoutResponse) {
                            // Check if logout was successful
                            if (logoutResponse.success) {
                               
                                button.text(kwf_translate.disconnected_classroom);
                                NProgress.done();
                                clearInterval(interval);
    
                                // Step 3: Send Success Message
                                jQuery(document).trigger(
                                    'bb_trigger_toast_message',
                                    [
                                        '',
                                        '<div>' + kwf_translate.disconnected_message + '</div>',
                                        'info',
                                        null,
                                        true
                                    ]
                                );
                                 // Trigger custom event for successful logout
                                console.log(logoutResponse.data)
                                
                                 // Dispatch a custom event after successful logout
                                var logoutEvent = new CustomEvent('logoutSuccess', {
                                    detail: {
                                        message: 'You will be logged out.'
                                    }
                                });
                                window.dispatchEvent(logoutEvent);
                              

                                // Notify the user in their browser
                                 
                                    /* console.log(logoutResponse.data.redirect_url) */
                                /* setTimeout(() => {
                                    button.text(kwf_translate.disconnect_classroom);
                                }, 60000);  */               
                                                
                            } else {
                                // Handle logout failure
                                console.error('Logout failed:', logoutResponse.data);
                            }
                        },
                        error: function (error) {
                            // Handle logout error
                            console.error('Logout error:', error);
                        }
                    });
                } else {
                    // Handle sending member IDs failure
                    console.error('Sending member IDs failed:', response.data);
                }
            },
            error: function (error) {
                // Handle sending member IDs error
                console.error('Sending member IDs error:', error);
            }
        });
    });

我认为我应该使用 global.js 来处理注销

我想要的:**自动注销具有 $user_id 的用户并将其导航到主页,无论其当前页面如何。这应该在不需要刷新页面或单击按钮的情况下发生,并且它应该适用于具有 $user_id 的用户,而不是单击按钮的个人。 **

javascript php jquery ajax wordpress
1个回答
0
投票

我想你有两种方法可以实现你的需求

第一个是实现 websockets 以允许服务器和客户端之间的异步双向通信。我不知道在 PHP 中执行此操作的技术是什么,但我确信它们存在

其次是在客户端实施良好的老式轮询。基于某个时间间隔,使用 AJAX 发送 HTTP 请求,询问服务器以判断用户是否仍然登录。这不是最优雅的解决方案,但更简单,并且在 websocket 不可用时被大量使用(尚未引入或尚未得到主要浏览器的广泛支持)

© www.soinside.com 2019 - 2024. All rights reserved.