twitter bootstrap typeahead ajax ejemplo


Estoy tratando de encontrar un ejemplo de trabajo del elemento twitter bootstrap typeahead que hará una llamada ajax para rellenar su desplegable.

Tengo un ejemplo de autocompletar de jquery que define la url de ajax y cómo procesar la respuesta

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { minChars:3, max:20 };
    $("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

¿Qué necesito cambiar para convertir esto al ejemplo typeahead?

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { source:'/index/runnerfilter/format/html', items:5 };
    $("#runnerquery").typeahead(options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

Voy a esperar a que se resuelva el problema ' Add remote sources support for typeahead'.

Author: user, 2012-02-10

16 answers

Editar: typeahead ya no está incluido en Bootstrap 3. Fecha de salida:

Desde Bootstrap 2.1.0 hasta 2.3.2, puedes hacer esto:

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            return process(data.options);
        });
    }
});

Para consumir datos JSON como este:

{
    "options": [
        "Option 1",
        "Option 2",
        "Option 3",
        "Option 4",
        "Option 5"
    ]
}

Tenga en cuenta que los datos JSON deben ser del tipo mime correcto (application/json) para que jQuery los reconozca como JSON.

 290
Author: Stijn Van Bael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:15

Puede usar la bifurcación BS Typeahead que soporta llamadas ajax. Entonces usted será capaz de escribir:

$('.typeahead').typeahead({
    source: function (typeahead, query) {
        return $.get('/typeahead', { query: query }, function (data) {
            return typeahead.process(data);
        });
    }
});
 116
Author: bogert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-07 14:56:23

A partir de Bootstrap 2.1.0:

HTML:

<input type='text' class='ajax-typeahead' data-link='your-json-link' />

Javascript:

$('.ajax-typeahead').typeahead({
    source: function(query, process) {
        return $.ajax({
            url: $(this)[0].$element[0].dataset.link,
            type: 'get',
            data: {query: query},
            dataType: 'json',
            success: function(json) {
                return typeof json.options == 'undefined' ? false : process(json.options);
            }
        });
    }
});

Ahora puede hacer un código unificado, colocando enlaces "json-request" en su código HTML.

 69
Author: Thantifaxath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-31 11:32:20

Todas las respuestas se refieren a BootStrap 2 typeahead, que ya no está presente en BootStrap 3.

Para cualquier otra persona dirigida aquí buscando un ejemplo AJAX usando el nuevo post-Bootstrap Twitter typehead.js , aquí hay un ejemplo de trabajo. La sintaxis es un poco diferente:

$('#mytextquery').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  limit: 12,
  async: true,
  source: function (query, processSync, processAsync) {
    processSync(['This suggestion appears immediately', 'This one too']);
    return $.ajax({
      url: "/ajax/myfilter.php", 
      type: 'GET',
      data: {query: query},
      dataType: 'json',
      success: function (json) {
        // in this example, json is simply an array of strings
        return processAsync(json);
      }
    });
  }
});

Este ejemplo utiliza tanto síncrono (la llamada a processSync) como sugerencia asíncrona, por lo que verá que algunas opciones aparecen inmediatamente, luego se agregan otras. Puedes usar uno o el otro.

Hay muchos eventos enlazables y algunas opciones muy poderosas, incluido el trabajo con objetos en lugar de cadenas, en cuyo caso usaría su propia función personalizada display para representar sus elementos como texto.

 42
Author: Jonathan Lidbeck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 04:49:15

He aumentado el plugin original typeahead Bootstrap con capacidades ajax. Muy fácil de usar:

$("#ajax-typeahead").typeahead({
     ajax: "/path/to/source"
});

Aquí está el repositorio de github: Ajax-Typehead

 24
Author: Paul Warelis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-31 14:46:26

Hice algunas modificaciones en la interfaz de usuario de jquery.min.js:

//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...

// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....

// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`

Y añadir la siguiente css

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}

Funciona perfecto.

 5
Author: bmoers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-13 06:46:02

Uno puede hacer llamadas usando Bootstrap. La versión actual no tiene ningún problema de actualización de origen Problemas al actualizar la fuente de datos typeawead de Bootstrap con la respuesta posterior , es decir, el origen de bootstrap una vez actualizado se puede modificar de nuevo.

Por favor refiérase a continuación para un ejemplo:

jQuery('#help').typeahead({
    source : function(query, process) {
        jQuery.ajax({
            url : "urltobefetched",
            type : 'GET',
            data : {
                "query" : query
            },
            dataType : 'json',
            success : function(json) {
                process(json);
            }
        });
    },
    minLength : 1,
});
 2
Author: neoeahit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:30

Para aquellos que buscan una versión coffeescript de la respuesta aceptada:

$(".typeahead").typeahead source: (query, process) ->
  $.get "/typeahead",
    query: query
  , (data) ->
    process data.options
 2
Author: Hendrik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-24 23:24:13

Revisé este post y todo no quería funcionar correctamente y, finalmente, junté los bits de algunas respuestas, así que tengo una demostración 100% funcional y la pegaré aquí como referencia: pegue esto en un archivo php y asegúrese de que las inclusiones estén en el lugar correcto.

<?php if (isset($_GET['typeahead'])){
    die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('index.php?typeahead', { query: query }, function (data) {
            return process(JSON.parse(data).options);
        });
    }
});
</script>
 2
Author: l0ft13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-04 21:56:10

Estoy usando este método

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},
    {
    name: 'options',
    displayKey: 'value',
    source: function (query, process) {
        return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
            var matches = [];
            $.each(data, function(i, str) {
                matches.push({ value: str });
            });
            return process(matches);

        },'json');
    }
});
 2
Author: Krava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-22 19:14:19

ACTUALIZACIÓN: Modifiqué mi código usando este fork

También en lugar de usar $.cada uno lo cambié a $mapa sugerido por Tomislav Markovski

$('#manufacturer').typeahead({
    source: function(typeahead, query){
        $.ajax({
            url: window.location.origin+"/bows/get_manufacturers.json",
            type: "POST",
            data: "",
            dataType: "JSON",
            async: false,
            success: function(results){
                var manufacturers = new Array;
                $.map(results.data.manufacturers, function(data, item){
                    var group;
                    group = {
                        manufacturer_id: data.Manufacturer.id,
                        manufacturer: data.Manufacturer.manufacturer
                    };
                    manufacturers.push(group);
                });
                typeahead.process(manufacturers);
            }
        });
    },
    property: 'name',
    items:11,
    onselect: function (obj) {

    }
});

Sin embargo, estoy encontrando algunos problemas al obtener

Uncaught TypeError: No se puede llamar al método 'toLowerCase' de undefined

Como se puede ver en un post más reciente Estoy tratando de averiguar aquí

Espero que esta actualización sea de alguna ayuda para usted...

 1
Author: mmoscosa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:30

Pruebe esto si su servicio no devuelve el encabezado de tipo de contenido de la aplicación/json correcto:

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            var json = JSON.parse(data); // string to json
            return process(json.options);
        });
    }
});
 1
Author: Andres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-16 22:43:03

No tengo un ejemplo de trabajo para ti ni tengo una solución muy limpia, pero déjame decirte lo que he encontrado.

Si nos fijamos en el código javascript para TypeAhead se ve así:

items = $.grep(this.source, function (item) {
    if (that.matcher(item)) return item
  })

Este código utiliza el método "grep" de jQuery para hacer coincidir un elemento en la matriz de origen. No vi ningún lugar donde puedas enganchar una llamada AJAX, así que no hay una solución "limpia" para esto.

Sin embargo, una manera un tanto hacky que usted puede hacer esto es tomar ventaja de la forma en que el el método grep funciona en jQuery. El primer argumento de grep es la matriz de origen y el segundo argumento es una función que se utiliza para hacer coincidir la matriz de origen (observe que Bootstrap llama al "matcher" que proporcionó cuando lo inicializó). Lo que podría hacer es establecer el origen en una matriz de un elemento ficticia y definir el matcher como una función con una llamada AJAX en ella. De esa manera, ejecutará la llamada AJAX solo una vez (ya que su matriz de origen solo tiene un elemento en ella).

Esta solución no es solo hacky, pero sufrirá de problemas de rendimiento ya que el código TypeAhead está diseñado para hacer una búsqueda en cada pulsación de tecla (las llamadas AJAX realmente solo deben ocurrir en cada pocas pulsaciones de tecla o después de una cierta cantidad de tiempo de inactividad). Mi consejo es darle una oportunidad, pero siga con una biblioteca de autocompletar diferente o solo use esto para situaciones que no sean AJAX si tiene algún problema.

 0
Author: Aamer Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-13 17:17:29

Cuando use ajax, intente $.getJSON() en lugar de $.get() si tiene problemas con la visualización correcta de los resultados.

En mi caso solo obtuve el primer carácter de cada resultado cuando usé $.get(), aunque usé json_encode() del lado del servidor.

 0
Author: larsbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-16 07:42:38

Utilizo $().one() para resolver esto; Cuando se carga la página, envío ajax al servidor y espero a que termine. Luego pase el resultado a la función.$().one() es importante .Porque force typehead.js para adjuntar a la entrada una vez. perdón por escribir mal.

(($) => {
    
    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 states = [];
      $.ajax({
          url: 'https://baconipsum.com/api/?type=meat-and-filler',
          type: 'get'
      }).done(function(data) {
        $('.typeahead').one().typeahead({
            hint: true,
            highlight: true,
            minLength: 1
          },
          {
            name: 'states',
            source: substringMatcher(data)
          });
      })
      

})(jQuery);
.tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */
.tt-hint {
    width: 396px;
    height: 30px;
    padding: 8px 12px;
    font-size: 24px;
    line-height: 30px;
    border: 2px solid #ccc;
    border-radius: 8px;
    outline: none;
}

.tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}

.tt-hint {
    color: #999;
}

.tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */
    width: 422px;
    margin-top: 12px;
    padding: 8px 0;
    background-color: #fff;
    border: 1px solid #ccc;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    box-shadow: 0 5px 10px rgba(0,0,0,.2);
}

.tt-suggestion {
    padding: 3px 20px;
    font-size: 18px;
    line-height: 24px;
    cursor: pointer;
}

.tt-suggestion:hover {
    color: #f0f0f0;
    background-color: #0097cf;
}

.tt-suggestion p {
    margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

<input class="typeahead" type="text" placeholder="where ?">
 0
Author: ali karimi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-05 14:03:49
 $('#runnerquery').typeahead({
        source: function (query, result) {
            $.ajax({
                url: "db.php",
                data: 'query=' + query,            
                dataType: "json",
                type: "POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
        },
        updater: function (item) {
        //selectedState = map[item].stateCode;

       // Here u can obtain the selected suggestion from the list


        alert(item);
            }

    }); 

 //Db.php file
<?php       
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'TableName');

$sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
$sql->bind_param("s",$search_param);            
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $Resut[] = $row["name"];
    }
    echo json_encode($Result);
}
$conn->close();

?>

 -1
Author: Mohamed Ayed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-11 06:55:47