Home > front end >  Getting 302 found in ajax JQUERY request in Laravel
Getting 302 found in ajax JQUERY request in Laravel

Time:09-18

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

CodePudding user response:

modify the return in controller

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

to

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

CodePudding user response:

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']);

  • Related