14

Given this chunk of ajax that calls FriendsController@destroy

$.ajax({
    url:     '/dashboard/friends/' + id,
    type:    'DELETE',
    data:    { src: 'show' },
    success: function(response) {
    }
});

How can I return Redirect::route('dashboard.friends.index') inside FriendsController after the delete procedure is completed? I guess this is trying to return the response back to AJAX which doesn't know how to react.

I could just window.location.href = '/dashboard/friends' but I want to Flash a success message to the view which I can't do with AJAX.

Jared Eitnier
  • 7,012
  • 12
  • 68
  • 123
  • Why don't flash your success message in the success function, then wait 3 seconds before redirect with `window.location.href = '/dashboard/friends'` ? – Fractaliste Jan 17 '14 at 10:27

5 Answers5

11

I found the most easiest way of doing this. just use same url again in your ajax success. assuming friends is your route name then

$.ajax({
    url:     '/dashboard/friends/' + id,
    type:    'DELETE',
    data:    { src: 'show' },
    success: function(response) {
       window.location.href = "friends";
    }
});

this way you can just put redirect or flash session message if you want.

Priya
  • 1,359
  • 6
  • 21
  • 41
don
  • 607
  • 8
  • 10
3

i know this might be old question but if you want to return a dynamic route

return route('post.view', ['id' => $result]);

and in your front-end you will do

  success: function(response){
          window.location.replace(response);
          }
Ahmed Aboud
  • 1,232
  • 16
  • 19
2

Here is how I solved this issue on my own. For functions such as performing an AJAX delete of a model, it will prompt a confirmation modal, perform the delete, flash the message and redirect to the provided route.

Once setup it can be done dynamically by passing in the proper data attributes to the original delete button or link.

Community
  • 1
  • 1
Jared Eitnier
  • 7,012
  • 12
  • 68
  • 123
1

I came across the same problem and here is what did the tricks for me.

In your controller, you can flash the message using:

\Session::flash('success', __('locale.message'));

And then in your ajax response handler, you redirect to wherever you want

location.replace('/home');

Don't forget to add the login in your view to display the message, I.E:

 @if (session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        {{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
 @endif
naghal
  • 537
  • 3
  • 19
-1
if(data.success){

    var loc = window.location;
    window.location = loc.protocol+"//"+loc.hostname+"/admin/dashboard";
}
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49