Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel redirect to route from controller when called by AJAX

Tags:

php

laravel

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.

like image 919
Jared Eitnier Avatar asked Jan 17 '14 08:01

Jared Eitnier


2 Answers

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);
          }
like image 74
Ahmed Aboud Avatar answered Oct 16 '22 13:10

Ahmed Aboud


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.

like image 10
don Avatar answered Oct 16 '22 13:10

don