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?
You are losing the reference to the array
datasourceby assigning a new array. You will need to manipulate the array to avoid losing the reference to it.See it here.
Another option is caching the response. I personally prefer this method over the previous one.
You can use the
processcallback after sending the first request and cache the data. Onwards, use the cached data.See it here.
PHP is returning incorrect
Content-Type. Try$.ajaxinstead of$.post.Notice the
dataTypeis set tojson.You can also set the correct
Content-Typein PHP usingheader().