0

I am trying to log in a user with Ajax. I used the following code. But the problem is I can see the validation Error but when I tried to check username & password with existing database I got following Error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in Sorry User not found

How can I successfully log in a user by avoiding above error?

Login controller:

protected function login(Request $request)
{
    $validator = Validator::make($request->all(), [
       'email' => 'required|email',
        'password' => 'required',
    ]);

    if ($validator->passes()) {
        if (auth()->attempt(array('email' => $request->input('email'),
          'password' => $request->input('password')),true))
        {
            return response()->json('success');
        }
        return response()->json(['error'=>'Sorry User not found.']);
    }

    return response()->json(['error'=>$validator->errors()->all()]);
}

Ajax Part:

$(document).ready(function() {
    $("#loginBtn").click(function(e) {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        e.preventDefault();
        var email = $("input[name='user_email']").val();
        var password = $("input[name='user_password']").val();

        $.ajax({
            url: '{{ route('login') }}',
            type: 'POST',
            data: {
                email: email,
                password: password
            },
            success: function(data) {
                if ($.isEmptyObject(data.error)) {
                    alert(data.success);
                } else {
                    printErrorMsg(data.error);
                }
            }
        });

    });

    function printErrorMsg(msg) {
        $(".print-error-msg-login").find("ul").html('');
        $(".print-error-msg-login").css('display', 'block');
        $.each(msg, function(key, value) {
            $(".print-error-msg-login").find("ul").append('<li>' + value + '</li>');
        });
    }
});
linktoahref
  • 7,812
  • 3
  • 29
  • 51
User57
  • 2,453
  • 14
  • 36
  • 72

1 Answers1

1

Change the format of the response error from

return response()->json(['error'=>'Sorry User not found.']);

to

return response()->json([
    'error' => [
        'email' => 'Sorry User not found.'
    ]
]);
linktoahref
  • 7,812
  • 3
  • 29
  • 51