17

What I'm trying to do is to get a json object via Ajax and populate the Bootstrap Typeahead with just one kind of value.

Here is my code:

nameTypeHead: function () {
        var _self = this,
            searchInput = $('#nameTypeHead'),
            arr = [];

        function getArray() {
            $.ajax({
                url: '/Home/AutoComplete',
                type: 'post',
                dataType: 'json',
                data: { searchText: searchInput.val() },
                success: function (data) {
                    $.each(data, function () {
                        arr.push(this.Name);
                    });
                    return arr;
                }
            });
        }

        searchInput.typeahead({
            source: getArray()
        });
    } 

I receive the error that arr is null

I also tried with .parseJSON() but with no success:

$.each($.parseJSON(data), function () {
   arr.push(this.Name);
});

What can I do to show just the value Name of my Json Object in the Typeahed?

If in the Ajax Success I put alert(JSON.stringify(data)); it alert correctly my Json Object.

3
  • success callback doesn't have to return anything, being it an async call - check this example instead.
    – moonwave99
    Commented Sep 27, 2012 at 12:56
  • Also if I remove return arr; it doesn't work... Commented Sep 27, 2012 at 12:58
  • From your link I can not understand CoffeeScript. Where I should declare property: "name" Commented Sep 27, 2012 at 13:08

3 Answers 3

34

I made it from scratch:

$('#typeahead').typeahead({

    source: function (query, process) {
        return $.getJSON(
            'path/to/lookup',
            { query: query },
            function (data) {
                return process(data);
            });
    }

});

Where data is a simple JSON array like:

 [
   "John",
   "Jane",
   "Alfredo",
   "Giovanni",
   "Superman"
 ]

If your data array has got a different structure, just rearrange it before passing it to process() method.

You can find a live example here.

EDIT - based on your json data:

[
    {'id':'0', 'name':'John'},
    {'id':'1', 'name':'Jane'}, 
    {'id':'2', 'name':'Alfredo'},
    ...
}

The getJSON callback becomes:

function (data) {
    return process(data.map((x => x.name));
}); 
12
  • just one question, why I should add in the url +query ?!? Commented Sep 27, 2012 at 13:18
  • 1
    and my console log say: TypeError: typeahead.process is not a function Commented Sep 27, 2012 at 13:23
  • Well you are asking your server for stuff based on what you are typing - query string.
    – moonwave99
    Commented Sep 27, 2012 at 13:23
  • and I pass the value using data: { ... : ... } Commented Sep 27, 2012 at 13:25
  • 1
    Great answer. But you should write process(data); return; instead of return process(data);
    – Oleg
    Commented Jun 19, 2013 at 14:43
7

Checkout this gist. Does autocomplete, deals with fast typers, and caches

https://gist.github.com/mrgcohen/5062352

3
  • 1
    This should be the accepted answer. Much more sophisticated and efficient. Thanks for gist! Commented Aug 14, 2013 at 18:59
  • 1
    Came up with my own solution for this, but was not that great and I was unhappy with it. This one is nice and simple. -- Note for others, you barley need to add or do anything just copy in the code, change the URL of your getJSON. Works out of the box.
    – Mikolaj
    Commented Jun 10, 2015 at 19:26
  • Thanks glad you like it. There are some good gist forks of it too.
    – mc.
    Commented Jun 12, 2015 at 1:20
3

This is what worked for me:-

HTML Setup :

<!-- HTML Setup-->
<input type="text" id="my-typeahead" />

Javascript :

/* 
example remote-data-source
[
  {
    id:1,
    name:'Batman'
  },{
    id:2,
    name:'Superman'
  } 
]
*/

$('#my-typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
}, {
    name: 'myDataset',
    source: function(str, sync, async) {
        // abstracting out the "REST call and processing" in a seperate function
        restCall(str, async);
    },
    templates: {
        suggestion: function(user) {
            return '<div>' + user.name + '</div>';
        },
        pending: '<div>Please wait...</div>'
    }
});

// The function that will make the REST call and return the data
function restCall(str, async) {
    return $.ajax('http://url-for-remote-data-source/query?name=' + str, {
        // headers and other setting you wish to set-up
        headers: {
            'Content-Type': 'application/json',
        },
        // response
        success: function(res) {
            //processing data on response with 'async'
            return async(res.data);
        }
    });
}

References:

Typeahead Docs - Datasets : https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#datasets

Jquery **$.ajax()** : https://api.jquery.com/jquery.ajax/

Good Luck.

1
  • 1
    This works but make sure about the format of res variable in success response for your specific ajax call. Commented Apr 17, 2019 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.