Session::flash not working in ajax laravel 5

2019-08-31 01:34发布

问题:

I have action named getuser which is called by ajax.

Here is my ajax

var $_token = $('#token').val();
var BASE = "{{ URL::to('/') }}";
$.ajax({
        url: BASE + "/admin/user/test",
        type: 'POST',
        data: {type:type, id:id},
        headers: { 'X-XSRF-TOKEN' : $_token },
        success: function(data){
            // Success...
            console.log(data);
            location.reload();
        }
    }); 

Controller action,

public function getuser()
{
    Session::flash('message', 'This is a message!'); 
    Session::flash('alert-class', 'alert-danger');
    exit;
}

And into view i have code like this,

@if(Session::has('message'))
    <p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
@endif

But not working for me. Any suggestion?

回答1:

You can flash a session in your ajax request, hower this will not change the current view.
If you want to update the current page after an ajax request you will have to use a javascript callback and javascript code to do this.

Please read this post about the difference between client side and server side scripting.


Update:
You will never receive the flashed values set in your ajax request. Flashed session variables only last for one request. So when the action returns and the output is send back the the ajax request, the flashed variables are cleared.

The best way to solve this is to not use ajax or use actual session variables and clear them manualy.



回答2:

I came across this question being in exactly the same situation. I think however that I found a solution to displaying a flash masseges after performing an ajax request. The solution is to use

return back ()

or

return redirect()

I have tried writing variable to the session and then removing it - it works but it is not ideal solution. I tried to use Session::reflush - it did not work for me.

So my working code look like this:

in my view:

<li class="delete">
<a href="javascript:checkDelete({{$classified>id}});">@lang('Delete')</a>
</li>

<script>
function checkDelete(id) {
    if (confirm('Are you sure you want to delete this classified?')) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: "DELETE",
            url: '/classified/' + id,
            success: function(result) {
                location.reload();
            }
        });
    }
}
</script>

then in my controller

flash(__('Your classified was removed'))->warning()->important();

if (request()->expectsJson()) {
return response(['status' => 'deleted']);
}

return back();

This will sucessfuly flash to your current view. The packege I'm using here is https://github.com/laracasts/flash I hope it helps someone!