Laravel Ajax登录,成功后重定向到先前的url

时间:2022-10-20 08:25:06

Suppose I have a page A where auth middleware is being used. Because of no login it gets redirected to login page.

假设我有一个正在使用auth中间件的页面a。由于没有登录,它会被重定向到登录页面。

On login page I have custom ajax login system. On succesful login I want to redirect to page A with same url so that action can be completed.

在登录页面,我有定制的ajax登录系统。成功登录后,我想重定向到具有相同url的页面A,以便完成操作。

My code for login is like this:

我的登录代码是这样的:

public function postLogin(Request $request)
{

    $auth = false;
    $errors = [];

    $inputs = $request->all();
    $validator = $this->validator($inputs);

    if ($validator->fails()) {
        return response()->json([
            'auth' => false,
            'intended' => URL::previous(),
            'errors' => $validator->errors()
        ]);
    }

    $user = User::where('email', $request->get('email'))->first();

    if ($user && $user->is_active == 0) {
        $errors[] = "This account has been deactivated";
    } else if ($user && $user->confirm_token != null) {
        $errors[] = "Please verify your email in order to login";
    } else {

        $credentials = ['email' => $request->get('email'), 'password' => $request->get('password'), 'is_active' => 1];

        if (Auth::attempt($credentials, $request->has('remember'))) {
            $auth = true;
        } else {
            $errors[] = "Email/Password combination not correct";
        }

    }

    if ($request->ajax()) {          
        return response()->json([
            'auth' => $auth,
            'intended' => URL::previous(),
            'errors' => $errors
        ]);
    }

    return redirect()->intended(URL::route('dashboard'));

}

I am trying to get previous url through url()->previous() but it returns login page url. Can someone guide me in this please. Any improvements/help will be appreciated.

我试图通过url()->previous()获取之前的url,但它返回登录页面url。有人能给我指点一下吗?如有任何改进或帮助,我们将不胜感激。

I am using Laravel 5.4

我使用的是Laravel 5.4。

8 个解决方案

#1


4  

I have a very similar problem here: Ajax Auth redirect on Laravel 5.6

这里我有一个非常相似的问题:Ajax Auth重定向到Laravel 5.6

As @aimme (https://*.com/users/1409707/aimme) pointed out, Ajax calls are stateless, so basically you can't interact with backend.

正如@aimme (https://*.com/users/1409707/aimme)所指出的,Ajax调用是无状态的,所以基本上你无法与后端进行交互。

His suggestion and my suggestion is to pass in the URL the intended page to redirect to, or maybe in your case you could to it via post parameters, e.g.:

他的建议和我的建议是将要重定向到的页面传递到URL,或者在你的情况下,你可以通过post参数来重定向到它,例如:

return response()->json([
    'auth' => false,
    'intended' => $request->intended,
    'errors' => $validator->errors()
]);

#2


1  

It might help you

它可能会帮助你

Instead of these return redirect()->intended(URL::route('dashboard'));

而不是这些返回重定向()->的目的(URL::route('dashboard')));

use

使用

return redirect('dashboard');

#3


1  

URL::previous();

this method will help you get previous URL. and you can redirect user to there using jQuery somelike this:

此方法将帮助您获取以前的URL。你可以使用jQuery将用户重定向到那里

window.location.href = url; // <- you can try your url here.

Good Luck !!

祝你好运! !

#4


1  

First of all when you got a request in backend save the redirect()->intended();

首先,当后台收到请求时,保存重定向()->意图();

intended() checks if the session index url.intended exists and redirects to it by default or else redirect to $default='/' which can be overwritten.

planned()检查会话索引url是否存在,并在默认情况下重定向到它,或者重定向到可以重写的$default='/'。

then pass this URL when request success, example:

然后在请求成功时传递此URL,例如:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      window.location.href = data.url;
    }
  });
}

#5


1  

There is no need to do anything special for AJAX calls.

不需要为AJAX调用做任何特殊的事情。

Redirect the same way you normally would on the back-end after a form submission.

在提交表单之后,以通常的方式重定向后端。

return redirect()->route('dashboard');

On the front-end you just need to be sure that you use the redirected URL to change the window.location. This will cause the browser to refresh and go to the new page.

在前端,您只需要确保使用重定向URL来更改windows .location。这将导致浏览器刷新并进入新页面。

axios.post(url, formData).then(response => {
    window.location = response.request.responseURL;
});

This code snippet is for the popular Axios library but the same thing can be done with jQuery or vanilla JavaScript.

此代码片段用于流行的Axios库,但同样的事情也可以用jQuery或普通的JavaScript完成。

#6


1  

If I understand your problem correctly, the problem is that you're confusing the previous URL for the intended URL when you're trying to provide a URL to redirect to in your JSON response. The previous URL actually refers to the HTTP Referrer, not the intended URL, which is set in the session by Laravel's auth middleware.

如果我正确地理解了您的问题,那么问题是当您试图在JSON响应中提供要重定向到的URL时,您混淆了前面的URL作为预期的URL。前一个URL实际上是指HTTP Referrer,而不是由Laravel的auth中间件在会话中设置的预期URL。

The HTTP referrer is the page that initiates a request. If you are currently on page /foo and you click a link to a page /bar, the HTTP Referrer on /bar will be /foo. The same thing happens when you initiate an AJAX request, the page you're on will be the referrer of the end point you're hitting. In your case your login page is initiating the request to your login handler, via AJAX.

HTTP referrer是发起请求的页面。如果您当前在页/foo上,并且单击到页/bar的链接,/bar上的HTTP引用将是/foo。当初始化AJAX请求时,同样的事情也会发生,您所访问的页面将成为您正在访问的端点的引用。在您的情况下,您的登录页面正在通过AJAX向登录处理程序发起请求。

When you try to visit a page protected by Laravel's auth middleare, it is at that point Laravel sets a value for the intended URL in the session, before redirecting you to the login page. Laravel stores the intended URL in the session as url.intended (As you will be able to see in Illuminate\Routing\Redirector::intended, which is what redirect()->intended() calls). So all you need to do is grab that from the session.

当您试图访问由Laravel的auth middleare保护的页面时,Laravel将为会话中的预期URL设置一个值,然后将您重定向到登录页面。Laravel将会话中预期的URL存储为URL .intended(正如您在illumin\ Routing\Redirector:::intended一样,这是redirect()->意图()调用的值)。所以你所需要做的就是从会话中获取它。

if ($request->ajax()) {          
    return response()->json([
        'auth' => $auth,
        'intended' => session()->pull('url.intended') ?: URL::route('dashboard'),
        'errors' => $errors
    ]);
}

return redirect()->intended(URL::route('dashboard'));

Note: Using ->pull will remove the item from the session after it has been retrieved.

注意:使用->拉取将在获取该项后从会话中删除该项。

An easier way to do this would be just to grab the target URL from an intended RedirectResponse:

一个更简单的方法就是从RedirectResponse中获取目标URL:

$redirect = redirect()->intended(URL::route('dashboard'))

if ($request->ajax()) {          
    return response()->json([
        'auth' => $auth,
        'intended' => $redirect->getTargetUrl(),
        'errors' => $errors
    ]);
}

return $redirect;

#7


1  

Laravel 5.4 + support . not know for lower version

Laravel 5.4 +支持。不知道下版本

 return redirect()->back();

This will redirect to previous page from where you came .

这将重定向到您的前一页。

Ajax part

Ajax的一部分

 <script type="text/javascript">
    var url = "<?php echo url()->previous(); ?>";
    location.href = url;
 </script>

                OR simply javascript function
 history.go(-1);

Check for above and working fine for me please check for your code .

请检查以上并为我工作良好,请检查您的代码。

#8


0  

I solved it by making a hidden field in form containing url()->previous() value because no other way I was getting previous page i.e Page A url. I tried almost all above answers.

我通过在包含url()->previous()值的表单中创建一个隐藏字段来解决这个问题,因为没有其他方法可以获得先前的页I。e页面的url。我试了几乎所有的答案。

#1


4  

I have a very similar problem here: Ajax Auth redirect on Laravel 5.6

这里我有一个非常相似的问题:Ajax Auth重定向到Laravel 5.6

As @aimme (https://*.com/users/1409707/aimme) pointed out, Ajax calls are stateless, so basically you can't interact with backend.

正如@aimme (https://*.com/users/1409707/aimme)所指出的,Ajax调用是无状态的,所以基本上你无法与后端进行交互。

His suggestion and my suggestion is to pass in the URL the intended page to redirect to, or maybe in your case you could to it via post parameters, e.g.:

他的建议和我的建议是将要重定向到的页面传递到URL,或者在你的情况下,你可以通过post参数来重定向到它,例如:

return response()->json([
    'auth' => false,
    'intended' => $request->intended,
    'errors' => $validator->errors()
]);

#2


1  

It might help you

它可能会帮助你

Instead of these return redirect()->intended(URL::route('dashboard'));

而不是这些返回重定向()->的目的(URL::route('dashboard')));

use

使用

return redirect('dashboard');

#3


1  

URL::previous();

this method will help you get previous URL. and you can redirect user to there using jQuery somelike this:

此方法将帮助您获取以前的URL。你可以使用jQuery将用户重定向到那里

window.location.href = url; // <- you can try your url here.

Good Luck !!

祝你好运! !

#4


1  

First of all when you got a request in backend save the redirect()->intended();

首先,当后台收到请求时,保存重定向()->意图();

intended() checks if the session index url.intended exists and redirects to it by default or else redirect to $default='/' which can be overwritten.

planned()检查会话索引url是否存在,并在默认情况下重定向到它,或者重定向到可以重写的$default='/'。

then pass this URL when request success, example:

然后在请求成功时传递此URL,例如:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      window.location.href = data.url;
    }
  });
}

#5


1  

There is no need to do anything special for AJAX calls.

不需要为AJAX调用做任何特殊的事情。

Redirect the same way you normally would on the back-end after a form submission.

在提交表单之后,以通常的方式重定向后端。

return redirect()->route('dashboard');

On the front-end you just need to be sure that you use the redirected URL to change the window.location. This will cause the browser to refresh and go to the new page.

在前端,您只需要确保使用重定向URL来更改windows .location。这将导致浏览器刷新并进入新页面。

axios.post(url, formData).then(response => {
    window.location = response.request.responseURL;
});

This code snippet is for the popular Axios library but the same thing can be done with jQuery or vanilla JavaScript.

此代码片段用于流行的Axios库,但同样的事情也可以用jQuery或普通的JavaScript完成。

#6


1  

If I understand your problem correctly, the problem is that you're confusing the previous URL for the intended URL when you're trying to provide a URL to redirect to in your JSON response. The previous URL actually refers to the HTTP Referrer, not the intended URL, which is set in the session by Laravel's auth middleware.

如果我正确地理解了您的问题,那么问题是当您试图在JSON响应中提供要重定向到的URL时,您混淆了前面的URL作为预期的URL。前一个URL实际上是指HTTP Referrer,而不是由Laravel的auth中间件在会话中设置的预期URL。

The HTTP referrer is the page that initiates a request. If you are currently on page /foo and you click a link to a page /bar, the HTTP Referrer on /bar will be /foo. The same thing happens when you initiate an AJAX request, the page you're on will be the referrer of the end point you're hitting. In your case your login page is initiating the request to your login handler, via AJAX.

HTTP referrer是发起请求的页面。如果您当前在页/foo上,并且单击到页/bar的链接,/bar上的HTTP引用将是/foo。当初始化AJAX请求时,同样的事情也会发生,您所访问的页面将成为您正在访问的端点的引用。在您的情况下,您的登录页面正在通过AJAX向登录处理程序发起请求。

When you try to visit a page protected by Laravel's auth middleare, it is at that point Laravel sets a value for the intended URL in the session, before redirecting you to the login page. Laravel stores the intended URL in the session as url.intended (As you will be able to see in Illuminate\Routing\Redirector::intended, which is what redirect()->intended() calls). So all you need to do is grab that from the session.

当您试图访问由Laravel的auth middleare保护的页面时,Laravel将为会话中的预期URL设置一个值,然后将您重定向到登录页面。Laravel将会话中预期的URL存储为URL .intended(正如您在illumin\ Routing\Redirector:::intended一样,这是redirect()->意图()调用的值)。所以你所需要做的就是从会话中获取它。

if ($request->ajax()) {          
    return response()->json([
        'auth' => $auth,
        'intended' => session()->pull('url.intended') ?: URL::route('dashboard'),
        'errors' => $errors
    ]);
}

return redirect()->intended(URL::route('dashboard'));

Note: Using ->pull will remove the item from the session after it has been retrieved.

注意:使用->拉取将在获取该项后从会话中删除该项。

An easier way to do this would be just to grab the target URL from an intended RedirectResponse:

一个更简单的方法就是从RedirectResponse中获取目标URL:

$redirect = redirect()->intended(URL::route('dashboard'))

if ($request->ajax()) {          
    return response()->json([
        'auth' => $auth,
        'intended' => $redirect->getTargetUrl(),
        'errors' => $errors
    ]);
}

return $redirect;

#7


1  

Laravel 5.4 + support . not know for lower version

Laravel 5.4 +支持。不知道下版本

 return redirect()->back();

This will redirect to previous page from where you came .

这将重定向到您的前一页。

Ajax part

Ajax的一部分

 <script type="text/javascript">
    var url = "<?php echo url()->previous(); ?>";
    location.href = url;
 </script>

                OR simply javascript function
 history.go(-1);

Check for above and working fine for me please check for your code .

请检查以上并为我工作良好,请检查您的代码。

#8


0  

I solved it by making a hidden field in form containing url()->previous() value because no other way I was getting previous page i.e Page A url. I tried almost all above answers.

我通过在包含url()->previous()值的表单中创建一个隐藏字段来解决这个问题,因为没有其他方法可以获得先前的页I。e页面的url。我试了几乎所有的答案。