typeahead callback not working

I'm fairly new to Typeahead and cannot make it to work with callback. Sorry if this already has been asked, I cannot find an exact issue when I searched.

I had Typeahead working if the records are just coming from a variable with strings, but not when it is coming from the database. I'm not sure how I can code the callback correctly.

We are using MVC 6, and looks like this is typeahead.js 0.11.1.

WHAT WORKS:

var records = [ "Alabama", "Alaska", "Arizona" . . .];

var substringMatcher1 = function (records) {
    return function findMatches(searchString, callback) {

        var matches, substringRegex;
        matches = [];
        substrRegex = new RegExp(searchString, 'i');

        $.each(records, function (index, record) {
            if (substrRegex.test(record)) {
                matches.push(record);
            }
        });

        callback(matches);
    };
};

$('#field1').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
},
{
    name: 'records',
    source: substringMatcher1(records)
});

WHAT DOES NOT WORK:

var substringMatcher2 = function (records) {
    return function findMatches(searchString, callback) {

        $.ajax({
            url: "/Test/GetRecords/",
            cache: false,
            data: { searchString: searchString },
            type: "POST",
            success: function (data) {

                callback(data);  
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
    };
};

$('#field2').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
},
{
    name: 'records2',
    source: substringMatcher2()
});

Test/GetRecords correctly returns the filtered records (List of strings) based on the searchString, but nothing is displayed on the page. I debugged and data is correctly populated. (data = [New Jersey, New York, . . . ] when searchString is "new")

What am I missing? And is this scenario possible to work?

Any help will be greatly appreciated.

Thanks in advance!

Answers 1

  • This is the updated code that made it work for me, in case it helps somebody else:

    var substringMatcher2 = function (records) {
    return function findMatches(searchString, processSync, processAsync) {
    
        $.ajax({
            url: "/Test/GetRecords/",
            cache: false,
            data: { searchString: searchString },
            type: "POST",
            success: function (data) {
    
                processAsync(data);  
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
    };
    

    };


Related Articles