Shane
Shane

Reputation: 753

Autocomplete dropdown

I have an autocomplete search bar to search employee names.

Index.php

<script>
        $(document).ready(function() {

            $('input.employees').typeahead({
                name: 'employees',
                remote: 'mysql.php?query=%QUERY'

            });

        })
    </script>
        <form><font color='black'>
            <input type="text" name="employees" class="employees" placeholder="Search Employees...">

Autocomplete.php

if (isset($_REQUEST['query'])) {
    $query = $_REQUEST['query'];
    $sql = mysql_query ("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE '%{$query}%' OR name_last LIKE '%{$query}%'");
    $array = array();
    while ($row = mysql_fetch_array($sql)) {
        $array[] = array (
            'label' => $row['name_first'].', '.$row['name_last'],
            'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',

        );
    }
    //RETURN JSON ARRAY
    echo json_encode ($array);
}

This is working fine. However I would like to be able to click a result in the dropdown and go to another page. This needs to include one of the variables, employee_id. E.g http://example.com/new-page.php?id=employee_id

Is this possible?

Upvotes: 1

Views: 932

Answers (1)

himyata
himyata

Reputation: 338

You can do it with jQuery-ui autocomplete widget. After adding jquery-ui's javascript and css files, write the code like this:

$('.employees').autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST", 
                contentType: "application/json;charset=utf-8", 
                dataType: "json", 
                async: true,
                url: "Autocomplete.php",
                data: "{'query':'" + request.term + "'}",
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            value: item.value,
                            id: item.employee_id,
                            label:item.label
                        }
                    }))
                }
            })
        }
    }).data('ui-autocomplete')._renderItem = function (ul, item) {
        return $('<li></li>')
            .data('item.autocomplete', item)
            .append('<a href="yourPage.php?employee_id='+item.id+'">' + item.label + '</a>')
            .appendTo(ul);

}

Upvotes: 1

Related Questions