Lion Hunter Lion Hunter - 1 month ago 11
jQuery Question

Redirect a user after login with ajax validation to the same page where he was

I am using this function to validate a user (ajax login) for my wordpress website.

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

}
}
});
e.preventDefault();
});


After login the user is redirected to the home page not the page which he was on. I want the user to be redirected to the same page where he came from. How can i do this ?

Any kind help is appreciated.

Answer

PHP SOLUTION

I presume you are forming the ajax_login_object array in PHP. Probably using

wp_localize_script( 'your_script', 'ajax_login_object' , $ajax_login_object );

That is the usual WordPress method of passing data to a front end script anyway.

Try this PHP:

$ajax_login_object['redirecturl'] ="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 

Or try this from http://www.insertcart.com/get-current-page-url-in-wordpress/:

$ajax_login_object['redirecturl'] = esc_url(the_permalink());

Another alternative from http://mekshq.com/get-current-page-url-wordpress/ is:

global $wp;
$ajax_login_object['redirecturl'] = home_url(add_query_arg(array(),$wp->request));

JavaScript Solution

This is a pure JavaScript solution.

In JS window.location.href returns the current URL of the page. So in your code you could replace

document.location.href = ajax_login_object.redirecturl;

with

document.location.href = window.location.href;