简体   繁体   中英

Typeahead Sometimes Returns Undefined

I looked at some of the other answers to this problem, but none of them seemed to work for me. I have an input field that uses typeahead. It works most of the time, returning the correct values, but sometimes it returns undefined . Here is the .js file:

// Add entry item typeahead configuration
$(document).ready(function() {
    var items = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace("add_entry_item_name"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: "items.php?add_entry_item_name=%QUERY"
    });
    items.initialize();
    $("#add_entry_item").typeahead({
        hint: true,
        highlight: true,
        minLength: 2
        }, {
        name: "items",
        displayKey: "item_name",
        source: items.ttAdapter()
    });
});

Here is the items.php file:

// Getting an instance of the connection to the database server
$DB = DB::get_instance();

// Setting the header
header("Content-Type: application/json");

// Exiting if nothing is set
if (!isset($_GET["add_entry_item_name"])) {
    echo json_encode([]);
    exit();
}

// Querying the database and JSON encoding the result
echo json_encode($DB->query("SELECT item_ID, item_name FROM mytable WHERE item_name LIKE ?", array("%{$_GET['add_entry_item_name']}%")));

I have created my own database query function, so that's what you're seeing above. It works very well, so I'm 99% sure the problem lies elsewhere...

Here's a sample output (items.php?add_entry_item_name=tec):

[
    {
        "item_ID": 465,
        "item_name": "Tectonic energy"
    }
]

However, typing in "tec" to my input field returns two undefined s.

Any suggestions?

Bloodhound's datumTokenizer is configured wrong. It should be something like this

datumTokenizer: Bloodhound.tokenizers.obj.whitespace("item_name"),

datumTokenizer – A function with the signature (datum) that transforms a datum into an array of string tokens.

Here is the reference and here is a DEMO

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM