Laravel 5响应未触发$ .ajax({success})

时间:2015-03-26 23:52:40

标签: jquery ajax json http laravel

我有一个带jQuery的ajax请求,表单提交,控制器相应地响应ant执行所有登录逻辑,但$ .ajax成功函数不会触发。在两种情况下,错误功能会被触发。验证失败或用户输入错误密码。

任何帮助或建议将不胜感激。感谢。

ajax调用的代码:

(function() {
var submitAjaxRequest = function(e) {

    var form = $(this);

    var method = form.find('input[name="_method"]').val() ||  'POST';

    $.ajax({

        type: method,

        url: form.prop('action'),

        data: form.serialize(),

        success: function(data) {
            console.log(data);
            if( data.status === 200 ) {//redirect if not authenticated user.
                $( location ).prop( 'pathname', 'projects' );
                var errors = data.responseJSON;
                console.log(data.responseJSON);
            }
        },
        error: function(data) {
            if( data.status === 401 ) {//redirect if not authenticated user.
                $( location ).prop( 'pathname', 'auth/login' );
                var errors = data.responseJSON;
                console.log(data.responseJSON);
            }
            if( data.status === 422 ) {
            //process validation errors here.
            var errors = data.responseJSON; 

            errorsHtml = '<div class="alert alert-danger"><ul>';

            $.each( errors , function( key, value ) {
                errorsHtml += '<li>' + value[0] + '</li>'; 
            });
            errorsHtml += '</ul></di>';

            $( '#form-errors' ).html( errorsHtml ); 
            } else {

            }
        }
    });

    e.preventDefault();
};

$('form[data-remote]').on('submit', submitAjaxRequest);
})();

处理发布请求的方法:

public function postLogin(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');

    if ($this->auth->attempt($credentials))
    {
        return response(array('msg' => 'Login Successfull'), 200)
          ->header('Content-Type', 'application/json');
    }

    return response(array('msg' => $this->getFailedLoginMessage()), 401)
          ->header('Content-Type', 'application/json');

    }

2 个答案:

答案 0 :(得分:0)

我正在处理成功:函数参数错误,修复它并在类似的问题中发布了工作代码: https://stackoverflow.com/a/29291698/2254007

答案 1 :(得分:0)

我正在使用:

<button type="submit" onsubmit="validate()" >

function validate()
{
  ajax call; // it was supporting html5 validation
}

然后我用了:

<button type="button" onclick="validate()" >

function validate()
{
  ajax call; // here it was not supporting html5 validation 
             //but working for success and error part
}