0

we can use AJAX Post request to transfer value from view to Controller. I'm doing this and successfully passing value from view to Controller. But can I use AJAX Post request to transfer value from one view to another view? I am doing this as Laravel suggests. But unsuccessful in this. Am I doing something wrong? Please help. Thank you. Here is my code:

Page.blade.php:

<script>
    $(document).ready(function(){
            $('a#one').on('click', function () {
            var text=$(this).text();
            console.log(text);
            $.ajax({
                url: APP_URL+'/show',
                method: 'post',
                data: {
                    text: text
                },
                success: function(response){
                    console.log(response);
                }
            });
        });
    });
</script>

web.php:

Route::post('show','UserController@special');
Route::get('/show' , [
    'uses' => 'UserController@special1',
    'as' => 'show'
]);

Controller:

public function special(Request $request){
        $text = $request->input('text'); 
        echo " dsds ".$text;
        // do stuff with $text
        $projects=DB::table('projects')->where('projects.type', '=', $text)->get();
        return view('show',compact('projects'));
    }

You can see that I'm using compact function for transferring value to another view named show.blade.php, but it is not transferring value. How can I transfer it to show.blade.php? I know that using GET method one can easily transfer value. But I want to transfer it by using POST request.

3472948
  • 801
  • 4
  • 15
Knowledge Seeker
  • 526
  • 7
  • 25

1 Answers1

1

How Ajax Works

How Ajax Works

As you can see on Right Side Box 2nd Bullet point. When you make AJAX request, it has response which returns to original caller.

Your web.php and Controller seems fine. When you make AJAX request, it hits special function but when you return view('show',compact('projects')); it return your view as HTML response to AJAX Call (You can see html in your console log). So it means you can not load new view from ajax.

You can use regular Synchronous calls to load new. :)

OR if you only want to update content on same page you can refer to below link

How can I return a view from an ajax call in Laravel 5

Zedex7
  • 1,624
  • 1
  • 12
  • 21