Skip to content

Instantly share code, notes, and snippets.

@narendrans
Created April 17, 2014 16:11
Show Gist options
  • Select an option

  • Save narendrans/10995012 to your computer and use it in GitHub Desktop.

Select an option

Save narendrans/10995012 to your computer and use it in GitHub Desktop.
<?php
/*
This script provides a demo of minimialistic implementation of typeahead + mysql.
Last modified by Naren on 4/17/2014 12:01 PM ET
Schema:
Column Type
id int
name varchar(50)
*/
// Get the query variable value
$query = $_GET['query'];
// define the db parameters
define('DATABASE', '');
define('HOST', '');
define('USER', '');
define('PASSWORD', '');
// connect to db
$con = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// retrieve the results and push it in the array
$result = mysqli_query($con, "SELECT name FROM countries where name like '" . $query . "%'");
$array = array();
while ($row = mysqli_fetch_array($result)) {
array_push($array, $row['name']);
}
// echo the array in json format
print_r(json_encode($array));
?>
<!DOCTYPE html>
<html>
<head>
<title>Typeahead MYSQL tester</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap-typeahead.js"></script>
</head>
<body>
Country:
<input type="text" id="countries" data-provide="typeahead">
</body>
<script type="text/javascript">
$(document).ready(function () {
$('#countries').typeahead({
highlight: true,
source: function (query, process) {
$.ajax({
url: 'countries_ajax.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function (data) {
console.log(data);
process(data);
}
});
}
});
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment