XHotSniperX
XHotSniperX

Reputation: 722

Bootstrap typeahead autocompletion with the source loaded only once on pageload

I want to load the whole source data via jquery from the server but only once on pageload. I want to store it in a variable. The jquery part works but the input does not autocomplete. It does nothing. It works only if the source is written like source: ["blablabla","dadadada"].

This is my Javascript Code:

var datasource;          // this is the variable where my source will be stored

$.post("typeahead.php",
  {
    query: 'query'       // 'query' has no meaning ;)
  }, 
  function(data) {       // data looks like ["asd","fds"] thanks to json_encode on the server side
    datasource = data;
});

$('#searchInput').typeahead( {
  source: datasource
});

Server Side php code:

    /* connect to the db */
    $con = mysql_connect("localhost","fahrschulesql1","******");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    // Select Database
    $db_selected = mysql_select_db("fahrschulesql1", $con);
    if (!$db_selected) {
        die ("Select DB error: " . mysql_error());
    }
    $query = "SELECT Vorname, Nachname FROM Benutzer b, Fahrlehrer f WHERE b.BenutzerID = f.BenutzerID";
    $result = mysql_query($query) or die ("MySQL-Error: " . mysql_error());
    while($row = mysql_fetch_array($result)){
        $array[] = $row["Vorname"] . " " . $row["Nachname"]; 
    }
    echo json_encode($array);
    mysql_close($con);

What am I doing wrong?

Upvotes: 0

Views: 4625

Answers (2)

Alexander
Alexander

Reputation: 23537

You are losing the reference to the array datasource by assigning a new array. You will need to manipulate the array to avoid losing the reference to it.

var datasource = [];

$.post("typeahead.php", {
    query: 'query'
}, function(data) {
    /* Add the responses to the datasource, don't mess up the reference */
    [].push.apply(datasource, data);
});

$('#searchInput').typeahead({
    source: datasource
});

See it here.


Another option is caching the response. I personally prefer this method over the previous one.

You can use the process callback after sending the first request and cache the data. Onwards, use the cached data.

var cachedsource = (function(){
    var datasource = null;
    return function(query, process){
        if(datasource !== null) {
            /* use cached data */
            return datasource;
        } else {
            $.post("typeahead.php", {
                query: 'query'
            }, function(data) {
                /* cache data */
                datasource = data;
                process(datasource);
            });
        }
    };
})();

$('#searchInput').typeahead({
    source: cachedsource
});

See it here.


PHP is returning incorrect Content-Type. Try $.ajax instead of $.post.

$.ajax({
  url: "typeahead.php", 
  data: {
    query: 'query'
  },
  success: function(data) {
    /* cache data */
    datasource = data;
    process(datasource);
  },
  dataType: "json"
});

Notice the dataType is set to json.

You can also set the correct Content-Type in PHP using header().

header('Content-Type: application/json');
echo json_encode($array);

Upvotes: 3

Filippo oretti
Filippo oretti

Reputation: 49813

where is your html code?

are you using this:

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

?

then be sure your callback is ok in firebug and data is returned cause you didn't specified any url for example here:

$.post("typeahead.php",

then be sure you are running your js inside document.ready

$(document).ready(function(){

//do my js
});

also try:

console.log(datasource); before passing that var to the bootstrap plugin

definitely try this:

$(function(){

$.post("typeahead.php",
  {
    query: 'query'       // 'query' has no meaning ;)
  }, 
  function(data) {       // data looks like ["asd","fds"] thanks to json_encode on the server side
    $('#searchInput').typeahead( {
  source: data
});
});

});

Upvotes: 0

Related Questions