Search code examples
javascriptjqueryajaxtypeahead.jsbloodhound

Ajax Jquery object not working like javascript's object


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


Solution

  • 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.