[SOLVED] Autocomplete search as you type

Hi, Im trying to do autocomplete using AJAX and slim3 / twig.

I have look at the system log, don’t see errors. it’s just the ajax don’t work, no results and the fetchdata route don’t get called. I haven’t worked with ajax, so my code could be wrong. any other solution of doing autocomplete, recommendations please

my 2 routes

$app->post('/fetchdata', App\Controllers\HKController::class . ':fetchdata'))->setName('fetchdata');
$app->get('/autocomplete', App\Controllers\HKController::class . ':autocomplete')->setName('autocomplete');

fetchdata

public function fetchdata(Request $request, Response $response) {
               
        $userlst = DB::table('usergroup')
                ->select(
                        'id',
                        'firstname',
                 )
                ->get();
        
        $userlst = json_encode($userlst);
       
       // dump($userlst);
       
         return $userlst;
         //return $this->view->render($response, 'base/autocomplete.twig', compact('userlst'));
     }

autocomplete

public function autocomplete(Request $request, Response $response) {

        return $this->view->render($response, 'base/autocomplete.twig');
    }

autocomplete.twig

{{ dump() }}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Create a jQuery UI Autocomplete with PHP and Ajax? - Nicesnippets.com</title>
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-11">
                <div class="card m-auto" style="width: 78%;">
                    <div class="card-header text-center text-white bg-primary">
                        <h4>How to Create a jQuery UI Autocomplete with PHP and Ajax? - Nicesnippets.com</h4>
                    </div>
                    <div class="card-body">
                        <form>
                            <div class="mb-3">
                                <label class="mb-1"><strong>Single selection :</strong></label>
                                <input type='text' id='autocomplete' class="form-control">          
                            </div>
                            <div class="mb-3">
                                <label class="mb-1"><strong>Selected User id :</strong></label>
                                <input type='text' id='selectuser_id' class="form-control">
                            </div>

                        </form>             
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Script -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script type='text/javascript' >
        $(function() {
            $("#autocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: "{{ route('fetchdata') }}",
                        type: 'POST',
                        dataType: "json",
                        data: {
                            search: request.term
                        },
                        success: function(data) {
                            response(data);
                        }
                    });
                },
                select: function (event, ui) {
                    $('#autocomplete').val(ui.item.label); // display the selected text
                    $('#selectuser_id').val(ui.item.value); // save selected id to input
                    return false;
                },
                focus: function(event, ui){
                    $("#autocomplete").val(ui.item.label);
                    $("#selectuser_id").val(ui.item.value);
                    return false;
                },
            });

  
        });

        function split(val) {
            return val.split(/,\s*/);
        }

        function extractLast(term) {
            return split(term).pop();
        }
    </script>
</body>
</html>


I changed the url, to this, still not working. Anyone sample code where AJAX is used the correct way will help…

thanks

$("#autocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: '/fetchdata'
                        type: 'POST',
                        {#dataType: 'json',
                        async:      true,#}
                        data: {
                            search: request.term
                        },
                        success: function(data) {
                            response(data);
                        }
                    });

I’ts not so easy to give here some tips. In your case, I would first try to fix the routing issue. Because if the route does not match or the route handler is not getting called, then all the other code will also not work.

Thanks, for responding. I’m starting to understand how to troubleshoot AJAX it totally differs from troubleshooting PHP. Im new to AJAX. All my work I done was without AJAX, no need for it. But for this function to work I need to do AJAX

You may use the (Chrome) developer toolbar to inspect the network activity. This will make it easier to see the Ajax error message. Press F12 and open the “Network” tab.

Thanks Odan, the developer toolbar opens a new door to troubleshoot.

I found this YouTube clip useful. You still need to adapt it to be used by Slim.

Excellent Tip… thank you