Make a typeahead remote call to codeigniter controller

599 views Asked by At

I want to be able to make a remote data call from bloodhound using typeahead to model with codeigniter.

1

There are 1 answers

0
Andres Zapata On BEST ANSWER

So I was struggling a bit trying to get typeahead (twitter) remote data and codeigniter to work together, I dint't find a good example that fit with my needs. After a few hours I came up with the following code, hope it helps.

The View:

var proyectos = new Bloodhound({
  datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.proyecto_titulo); },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: 'proyectos/proyectos/getProyectos?query=%QUERY',
    wildcard: '%QUERY'
  } 
});

$('#titulo').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
 },
  {
  name: 'proyectos',
  displayKey: 'proyecto_titulo',
  source: proyectos.ttAdapter(),
  templates: {
    empty: [
      '<div class="empty-message">',
        'No se encontraron registros que coincidan con la búsqueda.',
      '</div>'
    ].join('\n'),
    suggestion: Handlebars.compile('<p>{{proyecto_titulo}} – <strong>{{tipo_proyecto_nombre}}</strong> </p>')
  }
});

The relevant part here is:

remote: { url: 'proyectos/proyectos/getProyectos?query=%QUERY', wildcard: '%QUERY' }

Where proyectos/proyectos is the controller path and getProyectos is the method that answers the request.

Whenever you type, and based on the minLength setting, is going to request a matching string in the back-end.

Note: In order to use the suggestion part in the templates setting, you must download the handlebars.js library.

The Controller:

public function getProyectos() {
        $consulta = $this->input->get('query');
        $proyectos = $this->proyectos_model->getProyectos($consulta);
        if($proyectos->num_rows() > 0){
            echo json_encode($proyectos->result());
        }
        else{
            echo '';
        }
    }

We first get the query string from the view with $this->input->get('query') and afterwards pass it to our model.

The Model:

public function getProyectos($consulta) {
         $query = $this->db->query
        ("select pro.proyecto_id
                ,pro.proyecto_titulo
                ,tip.tipo_proyecto_nombre
                ,tip.tipo_proyecto_id
                from proyectos pro 
                inner join tipos_proyectos tip on tip.tipo_proyecto_id = pro.tipo_proyecto_id 
                where pro.proyecto_titulo ilike '%" . $consulta . "%' ");
        return $query;
     }

Here in the model we simply pass the query string to our sql select statement and we're done. The database I'm using is postgresql.

I hope you find this helpful.