Search code examples
jqueryajaxlaravelsearchbar

Searching database with AJAX and Laravel's blade view


I'm trying to implement a search feature for an app I'm developing. I have already populated the database with content. So far I am getting the error of the following whenever i enter text into the text field. It has something to do with URL I'm passing into my AJAX.

NotFoundHttpException in RouteCollection.php line 161:

Main.js

$(document).ready(function(){

    $('#txtSearch').keyup(function(){


        var text = $('#txtSearch').val();

        var dataString = 'text=' + text;

        $.ajax({

            type: 'GET',
            url: "{{ URL::route('search') }}",
            data: dataString,

            success: function(response){

                alert(response);
            }

        });

    });

});

routes:

Route::get('/search', [

    'uses' => 'HomeController@getSearch',
    'as' => 'search'

]);

Controller:

class HomeController extends Controller
{
    public function getSearch(Request $request){

        return view('home');
    }
}

Solution

  • Change the following line:

    url: "{{ URL::route('search') }}",
    

    to

    url: '/search',
    

    And try again. As the Ajax code you are using in written in a JS file and you cannot use blade syntax in JS file.