2016-06-09 67 views
1

我在L5.2中創建一個CRUD系統,並使用Bootstrap Modal來顯示錶單。我已經使用BootFormsLaravel Bootstrap Modal Form驗證窗體並在Modal中顯示錯誤消息而不關閉它。Laravel 5.2&AJAX - 在重定向後顯示成功消息

基本上我打開在同一頁上的模式內添加/編輯表單,表單驗證在Modal中完成,一旦一切正常,數據將被插入到數據庫中並且模式關閉。之後,頁面刷新並顯示更新的數據。

一切工作正常,除了成功的情況下,我無法在我的網頁上顯示成功消息。

以下是我的代碼:

AJAX

$.ajax({ 
    type: "POST", 
    url: url, 
    data: data, 
    dataType: 'json', 
    cache: false, 
    contentType: contentType, 
    processData: false 

// Response. 
}).always(function(response, status) { 

    // Reset errors. 
    resetModalFormErrors(); 

    // Check for errors. 
    if (response.status == 422) { 
     var errors = $.parseJSON(response.responseText); 

     // Iterate through errors object. 
     $.each(errors, function(field, message) { 
      console.error(field+': '+message); 
      var formGroup = $('[name='+field+']', form).closest('.form-group'); 
      formGroup.addClass('has-error').append('<p class="help-block">'+message+'</p>'); 
     }); 

     // Reset submit. 
     if (submit.is('button')) { 
      submit.html(submitOriginal); 
     } else if (submit.is('input')) { 
      submit.val(submitOriginal); 
     } 

    // If successful, reload. 
    } else { 
     location.reload(); 
    } 
}); 

控制器:

public function store(CustomerRequest $request) 
{ 
    Customer::create($request->all()); 

    return redirect('customers') 
     ->with('message', 'New customer added successfully.') 
     ->with('message-type', 'success'); 
} 

查看:(顯示成功消息)

@if(Session::has('message')) 
    <div class="alert alert-{{ Session::get('message-type') }} alert-dismissable"> 
     <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button> 
     <i class="glyphicon glyphicon-{{ Session::get('message-type') == 'success' ? 'ok' : 'remove'}}"></i> {{ Session::get('message') }} 
    </div> 
@endif 

你可以看到成功的情況下AJAX只是重新加載頁面,我希望它重定向到Controller函數中指定的頁面並顯示該成功消息。

回答

4

您正在返回來自響應的HTTP重定向,該響應不支持AJAX請求。諸如瀏覽器之類的客戶端將能夠攔截並使用頭部信息,然後重新加載頁面。

相反,爲您的特定問題,請考慮:

https://laravel.com/docs/5.2/session#flash-data

public function store(CustomerRequest $request) 
{ 
    Customer::create($request->all()); 

    $request->session()->flash('message', 'New customer added successfully.'); 
    $request->session()->flash('message-type', 'success'); 

    return response()->json(['status'=>'Hooray']); 
} 

現在,你的AJAX收到HTTP/200 OK響應將執行location.reload和閃現的會話數據將提供給視圖。

+1

你已經救了我的一天,布拉沃。 – Jazzbot

+0

你是否總是必須返回響應才能將數據放入會話中?因爲我只寫了這段代碼'$ request-> session() - > flash('message-type','success');'並且它不工作。爲什麼? – shigg