Jazzbot Jazzbot - 2 years ago 870
Ajax Question

Laravel 5.2 & AJAX - Display success message after redirect

I'm creating a CRUD system in L5.2 and am using Bootstrap Modal to display forms. I've used BootForms and Laravel Bootstrap Modal Form to validate forms and display error messages inside Modal without closing it.

Basically I'm opening Add / Edit forms inside a modal on same page, the form validation is done inside Modal and once everything is okay the data is being inserted in database and the modal closes. After that the page refreshes and shows updated data.

Everything is working fine, except in case of success I am not able to display a success message on my page.

Following is my code:


type: "POST",
url: url,
data: data,
dataType: 'json',
cache: false,
contentType: contentType,
processData: false

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

// Reset errors.

// 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')) {
} else if (submit.is('input')) {

// If successful, reload.
} else {


public function store(CustomerRequest $request)

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

View: (to display success 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') }}

You can see in case of success AJAX just reloading the page, I want it to redirect to the page specified in Controller function and display that success message.

Answer Source

You are returning a HTTP redirect from the response, which doesn't work with AJAX requests. A client such as a browser would be able to intercept and consume the header information which would then reload the page.

Instead, for your particular problem, consider:


public function store(CustomerRequest $request)

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

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

Now, the HTTP/200 OK response received by your AJAX will execute location.reload and the flashed session data will be available to the view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download