twitter bootstrap 3.0 typeahead ajax example

101,600

Solution 1

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);
            });
        }
    });
})
</script>

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.

Solution 2

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}

Solution 3

I'm using this https://github.com/biggora/bootstrap-ajax-typeahead

The result of code using Codeigniter/PHP

<pre>

$("#produto").typeahead({
        onSelect: function(item) {
            console.log(item);
            getProductInfs(item);
        },
        ajax: {
            url: path + 'produto/getProdName/',
            timeout: 500,
            displayField: "concat",
            valueField: "idproduto",
            triggerLength: 1,
            method: "post",
            dataType: "JSON",
            preDispatch: function (query) {
                showLoadingMask(true);
                return {
                    search: query
                }
            },
            preProcess: function (data) {

                if (data.success === false) {
                    return false;
                }else{
                    return data;    
                }                
            }               
        }
    });
</pre>   
Share:
101,600

Related videos on Youtube

Pascal Klein
Author by

Pascal Klein

I learned coding in university and founded three startups, in all three of them i was responsible for Frontend Development and Online Marketing. Currently I am working on an online marketplace for short term work: InStaff - Book Hostesses &amp; Eventstaff online I know PHP, Javascript, Java and some Objective-C. I also got to know a little bit of Scala, Python and Octave in my free time. Most of my developer time I worked on web- and mobile applications with Kohana, jQuery Mobile and Android.

Updated on July 09, 2022

Comments

  • Pascal Klein
    Pascal Klein almost 2 years

    There are a lot of typeahead ajax examples out there for bootstrap 2, for example this here twitter bootstrap typeahead ajax example.

    However I am using bootstrap 3 and I could not find a complete example, instead there are just a bunch of incomplete information snippets with links to other websites, for example this here Where is the typeahead JavaScript module in Bootstrap 3 RC 1?

    Could someone please post a fully working example on how to use typeahead with bootstrap 3, if you load the data from the server via ajax, every time the user changes the input.

    • Zim
      Zim about 10 years
      This example works for Bootstrap 3 bootply.com/86571
    • Pascal Klein
      Pascal Klein about 10 years
      @Baghoo, I was looking for an example that is getting the data remotely via Ajax.
  • Pascal Klein
    Pascal Klein about 10 years
    What do you mean upgrading? Can you rather please just enter a valid example here.
  • netcult
    netcult about 10 years
    I meant if you have a working typeahead for bootstrap2, you can upgrade using this info. The second link might be more helpfull for you?
  • raider33
    raider33 over 9 years
    where did you get the styles from? With out them, it is terrible in my BS-3 project. With the styles, it looks great.
  • wwkudu
    wwkudu over 9 years
    @raider33 I think I got them from inspecting the page at Twitter Typeahead Examples. I may have had to adjust slightly to fit with my project styles.
  • Pascal Klein
    Pascal Klein over 9 years
    What is this Bloodhound Class? And could you please reather post javascript then coffeescript. I know I could convert it, but I think everybody wo can read coffee, can read plain javascript, but not the other way round.
  • wwkudu
    wwkudu over 9 years
    @PascalKlein Bloodhound is the suggestion engine, the code that decides which options to bring back based on what has been typed so far. More docs at the TypeAhead page. In their words, there are two parts to type ahead: the UI view (Typeahead) and the suggestion engine (in this case Bloodhound).
  • Pascal Klein
    Pascal Klein over 9 years
    This is for Twitter Bootstrap 2.0+
  • magicrebirth
    magicrebirth over 9 years
    github.com/bassjobsen/Bootstrap-3-Typeahead was the quickest way to upgrade for me too
  • johnnyRose
    johnnyRose over 8 years
    This answer could be improved if it weren't 100% code.
  • Keith
    Keith about 8 years
    That link is dead, please put content in the answer, rather than linking to it externally.
  • Christof
    Christof about 8 years
    Thanks for your example. "making sure that the div id, not the input id, is the one referred to in the script" -> you're actually referring to $("#getLearnerLike .typeahead"), which is the input field within that div.
  • Anupam
    Anupam about 7 years
    super. Couldnt find a complete example in the docs. This answer helps a lot
  • Anupam
    Anupam almost 7 years
    Found a good example here too: tatiyants.com/…
  • BASEER HAIDER JAFRI
    BASEER HAIDER JAFRI about 6 years
    Work fine but unfortunately suggestion drop down.
  • Powerriegel
    Powerriegel over 4 years
    What does process??