0

I'm using ajax request in Laravel and passing CSRF token also but some times my application gets stuck and getting this error :

enter image description here

Code :

  var formData = $(this).serialize();
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    });
    $.ajax({
        url:$(this).attr('action'),
        type:'POST',
        data:formData,
        headers: {
            Accept: "application/json"
        },
        success:function(response) {

This form is in modal popup :

 <form id="user-login" class="login" action="{{ url('login') }}" method="post">
 {{ csrf_field() }}

Controller :

  public function login(Request $request)
    {  
        $validator = Validator::make($request->all(),[
            'email' => ['required'],
            'password' => ['required', 'string', 'min:5'],
        ]);
        if ($validator->passes()) {
        if (\Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password, 'status' => 'active','isAdmin'=>'0']) || \Auth::guard('user')->attempt(['contact_number' => $request->email, 'password' => $request->password, 'status' => 'active','isAdmin'=>'0'])) {
            $request->session()->regenerate();
            return response(['success' => true,'message'=>'Successfully Login'], 200);
         }
        else
        {
            $message = 'Invalid username or password';
            return response()->json(['success'=>false,'message' => $message]);
        }
    }
    return Response::json(['errors' => $validator->errors()]);
    }

Route:

Route::post('/user-login', 'Auth\UserRegisterController@login')->name('user-login');

RedirectIfAuthenticated Middleware:

 public function handle($request, Closure $next, $guard = null)
    {
        if ($guard == "employee" && Auth::guard($guard)->check()) {
                return redirect(RouteServiceProvider::EMPLOYEE_HOME);
        }

        if (Auth::guard($guard)->check()) {
            return redirect(RouteServiceProvider::HOME);
        }

        return $next($request);
    }

Any solution, Thanks

blue pine
  • 472
  • 6
  • 17
user3653474
  • 3,393
  • 6
  • 49
  • 135

2 Answers2

0

modify the return in controller

return response(['success' => true,'message'=>'Successfully Login'], 200);

to

return response->json(['success' => true,'message'=>'Successfully Login'], 200);
Hamis Hamis
  • 84
  • 2
  • 9
0

You should try a couple of things.

  1. It can be due to the middleware of an outer group that was redirecting the request

  2. Your ajax setup to this. to make sure you're grabbing the token

    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '<?= csrf_token() ?>' } });

  3. Make sure you return the response properly.

    return response(['status' => true, 'message' => 'Success']);

  • This is a comment, not an answer. The Token is "grabbed" and would throw a 419 error. The way you return the response in point 3 is missing `->json()` – Gert B. Sep 17 '21 at 06:45