Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

carlosmtns's avatar

Controller don't return view after AJAX post

Hi guys,

I'm struggling with a little problem for a few days and maybe you could enlight me up.

Imagine that I have a form with two inputs to let the user find a book (by name and category). And on submit, he´s redirected to a page listing the results.

I've done this with a GET method, but as a GET my url turns in something like: http://localhost:8000/en/search?search_book=NAME&type_select=CATEGORY

route:

Route::get('/search', 'BookController@findBooks')->name('search');

Now I'm looking for something cleaner like http://localhost:8000/en/search/NAME/CATEGORY

For this, I've changed my route to

Route::post('/search/{name}/{category}', 'BookController@findBooks')->name('search');

Added two parameter on my controller. (This controller simply run a few queries and return a view with the results.)

And changed my form submit mode. Now I'm submit the request by AJAX call.

<script type="text/javascript">
        var frm = $('#form_sub');

        frm.submit(function (e) {

            e.preventDefault();
            var name = $('#bk_name').val(); 
            var category = $('#bk_category').val(); 

            var url = '{{ route("search", [":name", ":category"] ) }}';
            url = url.replace(':name', name);
            url = url.replace(':category', category);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('[name="_token"]').val()
                }
            });

            $.ajax({
                type: frm.attr('method'),
                url: url,
                data: frm.serialize(),
                dataType: 'html',
                success: function (data) {
                    $('body').html(data);
                },
                error: function (data) {
                    console.log('An error occurred.');
                },
            });
        });
    </script>

And now there's the problem. On submit I wont see any change on my browser. But I could see on Network tab (on preview) my page with the results.

I'm trying to understand, why my controller don't return the view as it should.

Any ideas? Or I'm doing it totally wrong way :( Thanks in advance for any help!

PS: The AJAX success function "$('body').html(data);" allow me visualize the view. Only the body is changed, the url remains the same http://localhost:8000/en/

0 likes
6 replies
carlosmtns's avatar

Hello @MaverickChan, there's my controller:

public function findBooks($name, $category)
    {
        $books = DB::table('books')
            ->join('book_category', function($join) use ($category)
                    {
                        $join->on('book_category.id', '=', 'books.category_id')
                             ->on('book_category.id', '=', DB::raw($category));

                    })
            -> select('books.id','book_category.short_name','books.name','books.price')
            -> where('books.name', 'LIKE', '%'.$name.'%')
            -> OrderBy('books.id')->Paginate(20);


        $bookimages = DB::table('books')
            -> join('book_images', 'books.id', '=', 'book_images.book_id')
            ->join('book_category', function($join) use ($category)
                {
                    $join->on('book_category.id', '=', 'books.category_id')
                         ->on('book_category.id', '=', DB::raw($category));

                })
            -> select('books.id','book_images.img_thumb')
            -> where('books.name', 'LIKE', '%'.$name.'%')
            ->get();

        $count_books = count($books);

        if($count_books > 0)
            return view('search', ['list'=>$books, 'listimages'=>$bookimages, 'search_name'=>$name, 'count_books'=>$count_books] )->withDetails($books);
        else return view('search')->withMessage('No details found for "'. $name .'". Try to search again!');
    }
jlrdw's avatar

See this example https://www.w3schools.com/php/php_ajax_database.asp

I think you are trying to update what's showing on page "on the fly", ajax skips

return view

and just updates / post the data.

I'd suggest watching some youtube videos on jquery ajax.

Edit: for what you want, I'd just do it the regular way and not use ajax / javascript.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

use javascript window.location.assign and build the url from the form fields.

<script type="text/javascript">
        var frm = $('#form_sub');

        frm.submit(function (e) {

            e.preventDefault();
            var name = $('#bk_name').val(); 
            var category = $('#bk_category').val(); 

            var url = '{{ route("search", [":name", ":category"] ) }}';
            url = url.replace(':name', name);
            url = url.replace(':category', category);

            window.location.assign(url);

    });
</script>
1 like
carlosmtns's avatar

Hello @Snapey That did the trick! Really appreciate for the help!

I follow your example and I only had to change my route from "post" to "get" again.

Thanks a lot you saved me ;)

Please or to participate in this conversation.