2015-02-07 73 views
2

嗨我真的很難在laravel 5中的新結構,我試圖通過AJAX提交表單,但我一直收到錯誤422(錯誤的請求)。我錯過了什麼,或者我需要使用我的請求類來做些什麼?這裏是我的代碼:Laravel 5 Ajax post

控制器:

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; 
}); 

所以我的問題是,當我提交我的表單,我可以從我的控制檯看到的是 - 無法加載資源:服務器respo狀態爲422(錯誤請求)

請如果有人能幫忙。提前致謝!

+1

你缺少代碼爲沒有它,我們無法真正幫助你。 – 2015-02-07 05:46:47

+1

你可以看看'app/storage/logs/laravel.log'併發布錯誤消息嗎?我想這是一個'TokenMismatchException'... – lukasgeiter 2015-02-07 10:13:46

+0

它現在正在工作。謝謝你的時間:) – user4269033 2015-02-08 02:25:48

回答

1

我其實只是在自己掙扎着,實際上答案很簡單。

由於Laravel的要求與422狀態碼響應,jQuery的成功/完成的功能不火,而是錯誤的功能,看到它不是200

因此,爲了得到JSON響應從Request對象因驗證失敗產生的AJAX請求,您需要定義錯誤處理程序,在您的情況如下:

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

我有一個類似的問題,我會離開這裏的代碼,我結束了。

形式:

<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'); 

}