-1

I am using the typeahead JS to setup typeaheads in my controls.

the code to input the array of class objects is like this:

        var companylist2 = [
            { word: "Alabama" },
            { word: "Alaska" },
            { word: "Arizona" },
            { word: "Arkansas" },
            { word: "California" },
            { word: "Colorado" }
        ];


        // Get Company Name Typeahead
        var states = new Bloodhound({
            datumTokenizer: function (d) {
                return Bloodhound.tokenizers.whitespace(d.word);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 5,
            local: companylist2
        });

However I want to set it dynamically from my backend so I used Ajax Jquery to populate a array of class objects like this:

        $(function () {
            $.ajax({
                type: "POST",
                url: "mypage.aspx/getCompanylist",
                contentType: "application/json",
                dataType: "json",
                success: function (msg) {
                    companylist = msg.d;
                    alert(companylist[0]["word"]);
                    alert(companylist[1]["word"]);
                }
            });
        });

The alert for companylist[0]["word"] and companylist[1]["word"] both display what I want it to display but when I change the source to the one from my JQuery, the typeahead doesn't work

LuxuryWaffles
  • 1,518
  • 4
  • 27
  • 50

1 Answers1

0

Try to config Typeahead in success

$(function () {
    $.ajax({
        type: "POST",
        url: "mypage.aspx/getCompanylist",
        contentType: "application/json",
        dataType: "json",
        success: function (msg) {
            companylist = msg.d;
            alert(companylist[0]["word"]);
            alert(companylist[1]["word"]);

            // Get Company Name Typeahead
            var states = new Bloodhound({
                datumTokenizer: function (d) {
                    return Bloodhound.tokenizers.whitespace(d.word);
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                limit: 5,
                local: companylist
            });

        }
    });
});

Maybe Callback and Asynchronous help.

leaf
  • 1,624
  • 11
  • 16
  • moved it in and it works.. no idea why but my companylist was initiated outside the $(function – LuxuryWaffles Aug 23 '17 at 05:43
  • `$.ajax` 's `success` function is a asynchronous callback.See [Callback](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) and [Asynchronous](https://developer.mozilla.org/en-US/docs/Glossary/asynchronous). – leaf Aug 23 '17 at 06:21