2017-09-26 210 views
0

我發生了一個奇怪的問題&我無法弄清楚。Laravel 5.5:阿賈克斯不工作

Ajax表格提交不起作用Laravel 5.5雖然它在Laravel 5.2的作品。我的意思是相同的代碼適用於Laravel 5.2,但不適用於Laravel 5.5。我附上我的代碼,以便您能理解。

Html:

<form action="{{ url('/register') }}" method="POST" id="userRegistrationForm"> 
    ........... 
    ........... 
    <button type="submit">Register</button> 
    {{ csrf_field() }} 
</form> 

JS:

$('#userRegistrationForm').validate({ 
    rules:{ 
     ...... 
    }, 
    messages:{ 
     ...... 
    }, 

    submitHandler: function(form){ 
     /* alert('Submit success!') */ /* It works, that means this function works properly */ 

     /* But this not works */ 
     $.ajax({ 
      url: form.action, 
      type: form.method, 
      data: $(form).serialize(), 

      success: function(response){ 
       location.reload(); 
      }, 

      error: function(response){ 
       alert('error spotted'); 
      } 
     }); 
    } 
}); 

當我從提交註冊,jQuery驗證工作。但是表單默認提交模式,而不是Ajax。錯誤不會通過Javascript警報顯示。

回答

0

您必須停止阻止寫你這樣的代碼

$("#userRegistrationForm").submit(function(e) { 
     e.preventDefault(); 
    }).validate({ 
     messages:{..}, 
     rules: {...}, 

     submitHandler: function(form) { 

      $.ajaxSetup({ 
       headers: { 
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
       } 
      }); 
      $.ajax({ 
       url: form.action, 
       type: form.method, 
       data: $(form).serialize(), 

      success: function(response){ 
       location.reload(); 
      }, 

      error: function(response){ 
       alert('error spotted'); 
      } 
     }); 
      return false; //This doesn't prevent the form from submitting. 
     } 
    }); 
0

你設置你的meta標籤CSRF令牌?

<meta name="csrf-token" content="{{ csrf_token() }}">

您所設定的令牌後,您需要設置標題爲您的Ajax請求,所以你只需要你的Ajax請求之前,下面的代碼添加。

$.ajaxSetup({ 
      headers: { 
       'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
      } 
     }); 
$.ajax({ 
     url: form.action, 
     type: form.method, 
     ... : ...,