I'm building a autocomplete with Twitter typeahead using an ajax JSON call to my PHP file to get some data but it keeps displaying the following in the dropdown result list:
undefined
undefined
undefined
but when i do:
alert(data);
I get the right data displayed but somehow the autocomplete list keeps displaying undefined, I've read and tried multiple things by some articles here on StackOverflow, but I can't seem to get it to work.
I have to following jquery code:
$('.item-name .typeahead').typeahead(null,{
source: function (query, process) {
$.ajax({
url: 'ajaxItems.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
// alert(data);
process(data);
}
});
}
});
And my ajaxItems.php has the following code for testing purpose:
<?PHP
$results = array();
$results[] = 'jeans';
$results[] = 'sweater';
$json = json_encode($results);
print_r($json);
?>
The JSON output is as follows:
["jeans","sweater"]
I hope someone can shine some light on what I'm doing wrong or point me in the right direction.
edit I am using the following typeahead file: http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js
I had similar problems using source:
and I ended up using remote:
.
In your case, it would be something like this:
$('.item-name .typeahead').typeahead({
remote: 'ajaxItems.php?query=%QUERY'
});
Note that I deleted null
on typeahead(null,{
since I think it's not necessary but I might be wrong. Obviously, you'll have to use $_GET
instead of $_POST
but I think it's much easier this way.