Search code examples
phplaraveljquery-tokeninput

jQuery TokenInput not working (displaying search results ) with laravel


This is the javascript code I use in my page.

<script>
    $(document).ready(function() {
        $("#tokenfield").tokenInput("localhost/inkrasa3/public/hashes",
            {theme:"facebook",tokenLimit:5,preventDuplicates:true,tokenValue:"name"});
    });
</script>

And here is the route file.

Route::get('hashes',function(){
return "[{id: 1, name:\"hello\"},{id:2, name:\"sup\"}]";
});

What am I doing wrong? It works perfectly for hard coded array or an Json array printed by blade.
I have even tried this:

$(document).ready(function() { $("#tokenfield").tokenInput("localhost/inkrasa3/public/hashes", {theme:"facebook",tokenLimit:5,preventDuplicates:true,tokenValue:"name",method:"post"}); });

with the route:

`Route::post('hashes',function(){
$names[] = array('id' => 0, 'name' => 'hello');
$names[] = array('id' => 1, 'name' => 'sup');

return Response::json($names);

});` At both times I get 404 error when I looked in browser dev tools.


Solution

  • Your response should be of type "application/json".

    Try the following code for Laravel 4:

    Route::get('hashes', function()
    {
        $names[] = array('id' => 0, 'name' => 'hello');
        $names[] = array('id' => 1, 'name' => 'sup');
    
        return Response::json($names);
    });
    

    And for Laravel 5 replace the return statement with:

    return response()->json($names);

    example with dynamic response (Laravel 4)

    Route::get('hashes', function()
    {
        // submitted letters from TokenInput
        $letters = Input::get('q');
    
        // search in the column "name"
        $users = User::where('name', 'LIKE', '%' . $letters . '%')->get();
    
        return Response::json($users->toArray());
    });
    

    the user table of course :)

    +----+--------------+
    | id | name         |
    +----+--------------+
    |  1 | Peter        |
    |  2 | Andy         |
    |  3 | Walter       |
    |  4 | ...          |
    +----+--------------+