ShadyNicNack
ShadyNicNack

Reputation: 107

AJAX: How would I bind autocomplete feature on KeyUp to be able to use Keyboard key

How would I bind or use the so called "autocomplete" feature on to the code below in order to use the autocomplete features keyboard up, down and enter functionality, because currently my code doesn't have that. It is on wordpress template and it is just being controlled by mouse for right now.

<script>
$(document).ready(function(){
    $("#search-box").keyup(function(){
        $.ajax({
            type: "POST",
            url: "autocomplete.php",
            data:'keyword='+$(this).val(),        
            success: function(data){
                $("#suggesstion-box ").show();
                $("#suggesstion-box").html(data);               
            }
        });  
    }); 
});

function selectCountry(val) {
  $("#search-id").val(val);
  $("#suggesstion-box").hide();
}

function updateSearchBox(el) {
  $("#search-box").val($(el).html());   
}
</script>

I have tried using

 $("#search-box").keyup.autocomplete(function() {  

or

 $("#search-box").autocomplete(function() { 

or even

 $("#search-box").autocomplete.keyup(function() { 

But it doesn't pull the list. I know there is something wrong with my AJAX causing me to have this issue of keyboard is not working correctly. Any Suggestions?

Ok... I have changed my php to give out a json.

Autocomplete.php

<?php
include_once "functions.php";

     if(isset($_POST['keyword']))
    {
        $database = lookup_connectToDatabase();                     
        $result = pg_query($database, "SELECT country, id, state FROM customers WHERE country iLIKE '" . $_POST["keyword"] . "%' OR id iLIKE '" . $_POST["keyword"] . "%' ORDER BY country");

        if (!$result){
                echo "<div class='show' align='left'>No matching records.</div>";
        }else {

            while($row=pg_fetch_assoc($result)){

                $array[] = array(
                    'label' = $row['id'].': '.$row['country'].', '.$row['state'],
                    'value' = $row['id'],
                );

            } 
            echo json_encode ($array);
        }
    }                                                   
?>

But still doesn't seem to work right. What am I missing with this json?

Upvotes: 1

Views: 3459

Answers (1)

Twisty
Twisty

Reputation: 30893

I suspect you're looking for: http://jqueryui.com/autocomplete/#remote

In your script, this might look like:

$(document).ready(function(){
    $("#search-box").autocomplete({
        minLength: 0,
        source: "autocomplete.php",
        select: function(e, ui){
            $("#search-box").val(ui.item.label);
            $("#search-id").val(ui.item.value);
            return false;
        }
    });
});

See More: http://api.jqueryui.com/autocomplete/#option-source

String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

If you must use POST, this can be done, but it's a bit more complex.

Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete.

This might look like:

$(document).ready(function(){
    $("#search-box").autocomplete({
        minLength: 0,
        source: function(req, resp){
            $.ajax({
                type: "POST",
                url: "autocomplete.php",
                data:'keyword=' + req.term,
                success: function(d){
                    resp(d);
                }
            });
        },
        select: function(e, ui){
            $("#search-box").val(ui.item.label);
            $("#search-id").val(ui.item.value);
            return false;
        }
    });
});

These examples are untested since you did not provide example data.

Update

Based on your autocomplete.php file, I would suggest the following:

<?php
include_once "functions.php";

if(isset($_POST['keyword'])){
    $database = lookup_connectToDatabase();
    $result = pg_query($database, "SELECT country, id, state FROM customers WHERE country iLIKE '" . $_POST["keyword"] . "%' OR id iLIKE '" . $_POST["keyword"] . "%' ORDER BY country");
    $data = array();
    if ($result){
        while($row=pg_fetch_assoc($result)){
            $data[] = array(
                "label" => $row['country'].', '.$row['state'],
                "value" => $row['id'],
            );
        } 
    }
    header('Content-Type: application/json');
    echo json_encode ($array);
}
?>

This should return an Array of objects with label and value properties.

The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

If there are no matches, we'll just get an empty array in return. So let's say we get the following response:

[
  {
    "label": "United States, California",
    "value": 420 
  },
  {
    "label": "United States, New York",
    "value": 100 
  }
]

When one of these is selected, the select callback is executed and #search-box will receive the ui.item.label; #search-id will receive the ui.item.value.

Upvotes: 1

Related Questions