2

I want to use typeahead to retrieve postal codes remotely and it must be post, not get. The call returns following json in the console:

{suggestions: "L-6956 | IM GRUND | KEEN-SUR-DOHEEM"}
{suggestions: "L-6956 | OP DER MOUCK | KEEN-SUR-DOHEEM"}

But the result is not shown under the input field in order to select one of the results. Here is my code:

$('#txtPostalCode').typeahead(
  null,
  {
    name: 'txtPostalCode',
    displayKey: 'suggestions',
    minLength: 3,
    source: function (query, syncResults) {
      $.post('/hotbed/sggl/getpipedaddresses', {searchItem: query}, function (data) {
        syncResults($.map(data, function (item) {
          console.log(item.suggestions);
          return item;
        }));
      }, 'json');

    }
  });
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
cwhisperer
  • 1,478
  • 1
  • 32
  • 63

1 Answers1

3

According to typeahead API, server response should be marked as an Async and your response should be fetched using that asyncCB,

$('#txtPostalCode').typeahead({
  null
},
{
  name: 'txtPostalCode',
  displayKey: 'suggestions',
  minLength: 3,
  async: true,
  source: function (query, processSync, processAsync) {
    processSync(['This suggestion appears immediately', 'This one too']);
    return $.ajax({
      url: "/hotbed/sggl/getpipedaddresses", 
      type: 'POST',
      data: {searchItem: query},
      dataType: 'json',
      success: function (json) {
        // in this example, json is simply an array of strings
        return processAsync(json);
      }
    });
  }
});

since there is on open bounty for this question I cant mark it as duplicate but you might find more details at the following question,

Duplicate of this question

Daniel Netzer
  • 2,151
  • 14
  • 22
  • It was helpful but I would like to add, __async:true__ is not mendatory when you use 3 arguments in source function. And you dont need to return anything. mind if I edit? – Munim Munna Feb 13 '18 at 13:46
  • More then happy – Daniel Netzer Feb 13 '18 at 16:51
  • I have edited your answer, but reviewers are not appreciating...Accept it before it gets rejected :( – Munim Munna Feb 14 '18 at 18:51
  • thanks, now it is working like expected. But for completeness: where to find the typeahead api? Ajax is posting for every single character I type, how to insert a delay before requesting? next question: I have to call another route once the option selected. Where to do this? – cwhisperer Feb 16 '18 at 07:19
  • U can use something like debouce, or start checking only after 2-3 chars – Daniel Netzer Feb 16 '18 at 07:49