Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

Controller:

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

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

View: (to display success message)

@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

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.

like image 653
Jazzbot Avatar asked Jun 09 '16 10:06

Jazzbot


1 Answers

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:

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

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.

like image 151
Justin Origin Broadband Avatar answered Sep 28 '22 18:09

Justin Origin Broadband