How can I logout of wordpress using ajax? You can't use wp-login.php
, so we need to use admin-ajax.php
. I'm using the following code:
html (widget):
<form id="logout" action="logout" method="post">
<input class="submit_button" type="submit" value="<?php echo $lg_logout[$lang] ?>" name="submit">
<?php wp_nonce_field( 'ajax-logout-nonce', 'logoutsecurity' ); ?>
</form>
functions.php
add_action('init', 'ajax_login_init');
function ajax_logout_init(){
add_action( 'wp_ajax_ajaxlogout', 'ajax_logout' );
}
add_action('init', 'ajax_logout_init');
function ajax_logout(){
check_ajax_referer( 'ajax-logout-nonce', 'logoutsecurity' );
// kill session
wp_clear_auth_cookie();
wp_logout();
die();
}
and the ajax (js):
$('form#logout').on('submit', function(e){
$.ajax({
type: 'POST',
url: siteUrl+'/wp-admin/admin-ajax.php',
data: {
'action': 'ajaxlogout', //calls wp_ajax_nopriv_ajaxlogout
'logoutsecurity': $('form#logout #logoutsecurity').val() },
success: function(data){
console.log('tutu');
//relodlognwidget();
}
});
e.preventDefault();
});
What's wrong?
Thanks @zorg for the head-start. I see that you got this working. For anyone who comes here like I did and needs and ajax logout, here is a complete solution.
/** Set up the Ajax Logout */
if (is_admin()) {
// We only need to setup ajax action in admin.
add_action('wp_ajax_custom_ajax_logout', 'custom_ajax_logout_func');
} else {
wp_enqueue_script('custom-ajax-logout', get_stylesheet_directory_uri() . '/js/customAjaxLogout.js', array('jquery'), '1.0', true );
wp_localize_script('custom-ajax-logout', 'ajax_object',
array(
'ajax_url' => admin_url('admin-ajax.php'),
'home_url' => get_home_url(),
'logout_nonce' => wp_create_nonce('ajax-logout-nonce'),
)
);
}
function custom_ajax_logout_func(){
check_ajax_referer( 'ajax-logout-nonce', 'ajaxsecurity' );
wp_clear_auth_cookie();
wp_logout();
ob_clean(); // probably overkill for this, but good habit
echo 'adios!!';
wp_die();
}
And now for the JavaScript file. Which if you used the code above will be saved in the active theme folder, like this wp-content/themes/yourtheme/js/customAjaxLogout.js
Note: I'm using the form of jQuery.on that allows for the logout button to be created even after the JavaScript file has run. Since we have ajax logout, we may be loading other things with Ajax, even the logout button.
$(document).on('click','.logout', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: {
'action': 'custom_ajax_logout', //calls wp_ajax_nopriv_ajaxlogout
'ajaxsecurity': ajax_object.logout_nonce
},
success: function(r){
// When the response comes back
window.location = ajax_object.home_url;
}
});
});