Created
April 17, 2014 16:11
-
-
Save narendrans/10995012 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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)); | |
| ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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