I have a text field whereby a user can search for a last name. When they start typing then a search is performed on the database via php/ajax. This then displays names in an unordered list. At this point I am just trying to alert the id of that user if you click on the <li>.
PHP for the ajax call:
if ($_POST) {
    $search = "{$_POST['last_name']}%";
    $stmt = $link->prepare("SELECT `first_name`, `last_name`, `id` FROM `employees` WHERE `last_name` LIKE ? LIMIT 7");
    $stmt->bind_param("s", $search);
    $stmt->execute();
    $result = $stmt->get_result();
    $numRows = $result->num_rows;
    if ($numRows > 0) {
        echo "<ul id='myid'>";
        while ($row = $result->fetch_assoc()) {
            $first_name = sanitize($row['first_name']);
            $last_name = sanitize($row['last_name']);
            $id = sanitize($row['id']);
            echo "<li data-id='$id'>" . $last_name . " , " . $first_name . "</li>";
        }
        echo "</ul>";
    }
    else {
        echo "No results found";
    }
    $stmt->close();
}
jQuery
$(document).ready(function(){ 
            $( "#last_name" ).focus();
            $( "#last_name" ).keyup(function(){
            $( "#loading" ).show();
            var last_name = $( "#last_name" ).val();
                if(last_name.length > 2) {
                $.ajax({
                    type: 'POST',
                    url: 'functions/employee-search.php',
                    data: {last_name: last_name},
                    success: function(data) {
                        if(!data.error) {
                            $( "#result" ).html(data);
                             $( "#loading" ).hide();
                        }
                    }
                });
            }
                if(last_name.length < 1) {
                    $( "#result" ).html("");
                    $( "#loading" ).hide();
                }
                });
            $("#myid li").click(function() {
                 alert($(this).attr('id'));
        });
    });
HTML
<div class="row">
    <div class="col-md-6">
        <div class="form-group">
            <label class="control-label">Employee</label>
            <input type="text" class="form-control" name="last_name" placeholder="Search by surname" id="last_name" autocomplete="off">
            <div style="display:none" id=loading><img src="../plugins/images/ajax-loader.gif" /></div>
            <div id="result"></div>
        </div>
    </div>
</div>
 
     
     
    