Plugin makes /wp-login.php AJAX accessible.
The plugin basically hooks up to 'login_init', and listens to requests which have a Response-Type header set to 'json'. It also checks for $_REQUEST['RESPONSE_TYPE']
, if for some reason you can't set the request headers., (*1)
The best way to install is using Composer., (*2)
composer require redandblue/rnb-ajax-login
, (*3)
Traditional methods work too., (*4)
Code sample (ES6+, production usage requires you to use a Webpack or Rollup and Babel or Bublé):, (*5)
// ajax-login.js import 'whatwg-fetch'; export default function(){ const ajaxLogin = e => { const form = e.target; const data = new FormData(form); const headers = new Headers({ 'Response-Type': 'json' }); fetch(form.action, { method: 'POST', body: data, headers: headers, credentials: 'include' }) .then(response => response.json()) .then(response => { if(response.type === 'success'){ console.log(response.message); } else { console.error(response.message); } }); e.preventDefault(); }; Array.from(document.querySelectorAll('[action="/wp-login.php"]')).forEach(form => { form.addEventListener('submit', ajaxLogin); }); }
// main.js import ajaxLogin from './ajax-login.js'; ajaxLogin();
This allows you to AJAXify any standard WP login form. If the user has JavaScript disabled, it will gracefully fallback to the vanilla WordPress way., (*6)
You can also log the current user out by sending a request to admin_ajax.php?action=wp_ajax_logout., (*7)
The response will be similar, with either success or error in the response.type., (*8)