Tuesday, March 7, 2017

Blank page with json result after form submition with ajax

I'm tryin to use ajax to login to my web application, but when i submit the login form i get a blank page with json responses, for example on success login i get:

{"success":true}

On wrong credentials i get:

{"fail":true,"errors":"Email or password is incorrect"}

And on wrong email or password i get(validation error):

{"fail":true,"errors":{"email":["The email field is required."],"password":["The password field is required."]}}

My js file contains this piece of code:

$('#loginForm').submit('click',function(e){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    })

e.preventDefault();

var formData = $(this).serialize();

$.ajax({
    type: "POST",
    url: $(this).attr("action"),
    dataType: 'json',
    data: formData,
    success: function (data) {
        window.location.replace("localhost:8000");
    },
    error: function (data) {
        $.each(data.errors, function(index,value) {
            var errorDiv = '#'+index+'_error';
            $(errorDiv).html(value);
        });
    }
});
});

In my controller i have the login function:

public function login(Request $request){
        try{
            $validate = Validator::make($request->all(),[
                'email' => 'required|max:320',
                'password' => 'required|max:150',
                'remember_me' => 'nullable|accepted'
            ]);

        if($validate->fails()){
            return response()->json(array(
                'fail' => true,
                'errors' => $validate->getMessageBag()->toArray()
            ));
        }

        $rememberMe = $request->remember_me ? true : false;

        if(Sentinel::authenticate(['username'=>$request->email, 'password' => $request->password], $rememberMe)){
            return response()->json(array(
                'success' => true
            ));
        }
        elseif(Sentinel::authenticate(['email'=>$request->email, 'password' => $request->password], $rememberMe)){
            return response()->json(array(
                'success' => true
            ));
        }
        else{
            return response()->json(array(
                'fail' => true,
                'errors' => 'Email or password is incorrect'
            ));
        }
    }
    catch(ThrottlingException $e) {
        $delay = $e->getDelay();

        return redirect('/')->with('error',"After too many login attempts\n you've banned for $delay seconds!");
    }
    catch(NotActivatedException $e) {
        return redirect('/')->with('error','Your account is not activated!');
    }
    catch(Exception $e){
        return redirect('/')->with('error',$e->getMessage());
    }
}

I don't know why the jquery on success or fail isn't triggered. Thanks in advance!



via Arlind Hajdari

Advertisement