北城已荒凉 2017-12-04 08:24 采纳率: 0%
浏览 80

Laravel Ajax登录

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>');
        });
    }
});
  • 写回答

1条回答 默认 最新

  • weixin_33738555 2017-12-04 10:00
    关注

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

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能