Twitter typeahead not working with with ajax

96 views Asked by At

I'm quite inexpert with the frontend world and i'm trying to make this working.

$('#the-basics .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 6
}, {
    source: function (query, process) {
        return $.get('autocompleteCodiceFiscale', {
            codiceFiscale: query
        }, function (data) {
            //alert(JSON.stringify(data));
            return process(data.options);
        });
    }
}).on('typeahead:selected', function (evt, data) {
    //Mocking some data
    if (data.length >= 16) {
        $('#nome').val("Mohamed");
        $('#cognome').val("Shafik");
        $('#sesso').val("Maschio");
        $('#codiceRegionale').val("RomaB");
        $('#codiceFiscale').val("SHFMMD81D06Z336B");
        $('#dataNascita').val("6/04/1981");
        $('#indirizzo').val("Via della prova");
        $('#numeroCivico').val("123");
        $('#comune').val("Roma");
        $('#cap').val("00100");
        $('#telFisso').val("0612345678");
        $('#telMobile').val("3471234567");
        $('#email').val("[email protected]");
        $('#aslCircoscrizione').val("Roma IV");
    } else {
        // do other stuff
    }
});

This give no errors but does not show the returned data, the alert shows that the informations requested are returned correctly.

if i use it like this

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

var anagrafica = ['SHFMMD81D06Z336B - Mohamed Shafik - 06/04/1981',
    'SHFMMD81D06Z336B - Mohamed Shafik - 06/04/1982',
    'MRTCLG81D08G442B - Calogero Martello - 01/01/1981'
];

$('#the-basics .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 6
}, {
    name: 'anagrafica',
    source: substringMatcher(anagrafica)
}).on('typeahead:selected', function(evt, data) {
    //Mock
    if (data.length >= 16) {
        $('#nome').val("Mohamed");
        $('#cognome').val("Shafik");
        $('#sesso').val("Maschio");
        $('#codiceRegionale').val("RomaB");
        $('#codiceFiscale').val("SHFMMD81D06Z336B");
        $('#dataNascita').val("6/04/1981");
        $('#indirizzo').val("Via della prova");
        $('#numeroCivico').val("123");
        $('#comune').val("Roma");
        $('#cap').val("00100");
        $('#telFisso').val("0612345678");
        $('#telMobile').val("3471234567");
        $('#email').val("[email protected]");
        $('#aslCircoscrizione').val("Roma IV");
    } else {
        //do other stuff
    }
});

everything works fine.

My controller looks like this

@RequestMapping(value = { "autocompleteCodiceFiscale" }, method = RequestMethod.GET, produces="application/json")
    public @ResponseBody TempClass autocompleteCodiceFiscale(@RequestParam String codiceFiscale, ModelMap map) {
        List<AssistitoDTO> assistiti = //requested data from the db

        TempClass autocomplete = new TempClass();
        for(AssistitoDTO assistito : assistiti)
        {
            autocomplete.options = new ArrayList<String>();
          autocomplete.options.add(assistito.getAnagrafica().getCodiceFiscale() + " - " +
                             assistito.getAnagrafica().getCognome() + " " +
                             assistito.getAnagrafica().getNome() + " - " +
                             assistito.getAnagrafica().getDataNascita().getDay() + "/" +
                             assistito.getAnagrafica().getDataNascita().getMonth() + "/" +
                             assistito.getAnagrafica().getDataNascita().getYear());
        }       
        System.out.println("La string JSON è: " + new Gson().toJson(autocomplete));
        return autocomplete;
    }

    private class TempClass
    {
        public List<String> options;
    }

It looks ugly i know but i'm just testing why it's not working at the moment. I don't think that i need to show my css because it works correctly with the mock. By the way the suggestions aren't even getting populated, it's not a visual issue. I apologize for my english.

1

There are 1 answers

0
ermejo On

Oh god finally i solved it, i've chenged it quite a bit, and thats the result,

var people = new Bloodhound({
         datumTokenizer: Bloodhound.tokenizers.obj.whitespace('codiceFiscale'),
         queryTokenizer: Bloodhound.tokenizers.whitespace,
         remote: {
          url: 'autocompleteCodiceFiscale/?codiceFiscale=%QUERY',
         wildcard: '%QUERY'
         }
     });

     people.initialize();

     $('#the-basics .typeahead').typeahead({
       minLength: 6
     }, {
      limit: 10,
         name: 'people',
         display: 'codiceFiscale',
         source: people.ttAdapter(),
         templates: {empty: [
                               '<div class="empty-message">',
                               'Nessun assistito / assistibile trovato',
                               '</div>'
                            ].join('\n'),
                     suggestion: Handlebars.compile('<div><strong>{{codiceFiscale}}</strong> - {{cognome}} {{nome}} - {{dataNascita}}</div>')
         }
     }).on('typeahead:selected', function(obj, datum) {
         // Do stuff
     });
      </script>

and the controller has been modified too

@RequestMapping(value = { "autocompleteCodiceFiscale" }, method = RequestMethod.GET, produces="application/json")
 public @ResponseBody List<Temp> autocompleteCodiceFiscale(@RequestParam String codiceFiscale, ModelMap map) {
  List<AssistitoDTO> assistiti = //data from the DB
  List<Temp> autocomplete = new ArrayList<Temp>();
  for(AssistitoDTO assistito : assistiti)
  {
   Temp assTemp = new Temp();
   assTemp.codiceFiscale = assistito.getAnagrafica().getCodiceFiscale();
   assTemp.nome = assistito.getAnagrafica().getNome();
   assTemp.cognome = assistito.getAnagrafica().getCognome();
   assTemp.dataNascita = assistito.getAnagrafica().getDataNascita().getDay() + "/" +
          assistito.getAnagrafica().getDataNascita().getMonth() + "/" +
          assistito.getAnagrafica().getDataNascita().getYear();
   autocomplete.add(assTemp);
  }  
  System.out.println("La string JSON è: " + new Gson().toJson(autocomplete));
  return autocomplete;
 }
 
 private class Temp
 {
  public String codiceFiscale;
  public String nome;
  public String cognome;
  public String dataNascita;
 }

and it finally works like this.