Home » Php » php – Laravel redirect to route from controller when called by AJAX

php – Laravel redirect to route from controller when called by AJAX

Posted by: admin July 12, 2020 Leave a comment

Questions:

Given this chunk of ajax that calls [email protected]

$.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.

How to&Answers:

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.

Answer:

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.

Answer:

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

Answer:

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

Answer:

if(data.success){

    var loc = window.location;
    window.location = loc.protocol+"//"+loc.hostname+"/admin/dashboard";
}