Сообщение Laravel 5 Ajax

Привет, мне действительно сложно работать с новыми структурами в laravel 5, я пытаюсь отправить форму через сообщение AJAX, но продолжаю получать ошибку 422 (плохой запрос). Я что-то упустил или мне нужно что-то сделать с моим классом Request? Вот мой код:

Контроллер:

public function login(LoginRequest $request)
{

    if ($this->auth->attempt($request->only('email', 'password')))
    {
        return redirect("/");
    }

    return response()->json(['errors'=>$request->response]);
}

Файл LoginRequest (я добавил собственный метод ответа):

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson())
    {
        return response()->json($errors, 422);
    }

    return response()->json($errors);
}

Мой код ajax:

$("#form-login").submit(function(){

  var selector = $(this);
  $.ajax({
     url: selector.attr("action"),
     type: "post",
     data: selector.serialize(),
     dataType: "json",
  }).done(function(data){
     console.log(data);
     if(data.status == "failed"){
       alert("error");
     }else{
        alert("success");
     }
  });

  return false;
});

Итак, моя проблема в том, что когда я отправляю свою форму, все, что я вижу с моей консоли, это - Не удалось загрузить ресурс: сервер ответил статусом 422 (неверный запрос)

Пожалуйста, если кто-нибудь может помочь. Заранее спасибо!


person user4269033    schedule 07.02.2015    source источник
comment
Вам не хватает кода для вопроса, без него мы не сможем вам помочь.   -  person    schedule 07.02.2015
comment
Можете ли вы взглянуть на app/storage/logs/laravel.log и опубликовать сообщение об ошибке? Полагаю, это _2 _...   -  person lukasgeiter    schedule 07.02.2015
comment
Теперь работает. спасибо за уделенное время :)   -  person user4269033    schedule 08.02.2015


Ответы (2)


На самом деле я сам боролся с этим, и ответ на самом деле довольно прост.

Поскольку запрос Laravel отвечает кодом состояния 422, функции jQuery success / done не запускаются, а скорее функция ошибки, поскольку это не 200.

Итак, чтобы получить ответ JSON на ваш запрос AJAX, сгенерированный из объекта Request из-за сбоя проверки, вам необходимо определить обработчик ошибок в вашем случае следующим образом:

$.ajax({ /* ... */ })
    .done(function(response) { /* ... */ })
    .error(function(data) { // the data parameter here is a jqXHR instance
        var errors = data.responseJSON;
        console.log('server errors',errors);
    });
person thorne51    schedule 11.03.2015

У меня была аналогичная проблема, оставлю здесь код, который у меня получился.

форма:

<div class="container">
        <div class="text-center">
            <div class="title">{!!HTML::image("img/HERLOPS_Transparent_Blue.png") !!}</div>
            {!! Form::open(['data-remote','url' => '/auth/login', 'class'  => 'col-lg-4 col-lg-offset-4', 'id' => 'login_form']) !!}

                <div class="form-group">
                    <input type="email" class="form-control" id="email" name="email" placeholder="Your Email" value="{{ old('email') }}">
                </div>
                <div class="form-group">
                    <input type="password" class="form-control" id="password" name="password" placeholder="Your Password">
                </div>
                <button id="submit" type="submit" class="btn btn-primary">Login <i class="fa fa-sign-in"></i></button>
                <div style="clear:both">
                    <a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
                </div>

            {!! Form::close() !!}
            <div style="text-align:center" class="col-lg-4 col-lg-offset-4" id="form-errors"></div>
            <div style="clear:both"></div>
            <div class="quote">{{ Inspiring::quote() }}</div>
        </div>
    </div>

JQuery:

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

    var form = $(this);

    var method = form.find('input[name="_method"]').val() ||  'POST'; //Laravel Form::open() creates an input with name _method

    $.ajax({

        type: method,

        url: form.prop('action'),

        data: form.serialize(),

        success: function(NULL, NULL, jqXHR) {
            if(jqXHR.status === 200 ) {//redirect if  authenticated user.
                $( location ).prop( 'pathname', 'projects' );
                console.log(data);
            }
        },
        error: function(data) {
            if( data.status === 401 ) {//redirect if not authenticated user
                $( location ).prop( 'pathname', 'auth/login' );
                var errors = data.responseJSON.msg;
                errorsHtml = '<div class="alert alert-danger">'+errors+'</div>';
                $( '#form-errors' ).html( errorsHtml ); 
            }
            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);
})();

И, наконец, метод контроллера, который обрабатывает запрос входа в систему ajax,

/**
 * Handle an ajax login request to the application
 * 
 * @param \Illuminate\Http\Request $request
 * @param \Illuminate\Http\Response
 */ 
public function postLogin(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);// Returns response with validation errors if any, and 422 Status Code (Unprocessable Entity)

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

    if ($this->auth->attempt($credentials))
    {
        return response(['msg' => 'Login Successfull'], 200) // 200 Status Code: Standard response for successful HTTP request
          ->header('Content-Type', 'application/json');
    }

    return response(['msg' => $this->getFailedLoginMessage()], 401) // 401 Status Code: Forbidden, needs authentication
          ->header('Content-Type', 'application/json');

}
person Andres Zapata    schedule 27.03.2015