On google and facebook when typing in a search, it will automatically list a bunch of the top searches based on what you’ve typed so far under the search box. What is this called? And is there a tutorial to show how it’s done?
The only way I could imagine doing it is querying a MySQL database for suggestions but I can’t imagine it’s doing that for every letter a person types, and I also don’t know how to make the suggestions box dynamic (change as the person’s typing).
Google gives you 10 results every time you type a letter, and every time the browser waits for an answer from the google server. So I guess every time a request is made, and 10 results are sent back to the browser.
Javascript is used to send the request and display the answer, and the technique is called AJAX.
Well, here’s a simple description of how it works.
Write a PHP file which accepts a $_GET parameter ‘query’. This queries a MySQL database and outputs all matches:
<?php
include('db_connect.php');
$Term = MySQL_Real_Escape_String($_GET['Term']);
$QueryString = "SELECT Title FROM SomeTable WHERE title LIKE '{$QueryString}%'";
$Query = MySQL_Query($QueryString);
$Values = array();
while($Row = MySQL_Fetch_Array($Query)){
echo '<li>' . $Row['Title'] . '</li>';
}
Then you use JavaScript to grab the contents of the output of that, so for example your input box could have:
onkeydown="getPossibleSearches(value)"
Then write a getPossibleSearches function in JavaScript which makes a call to your PHP file with the value as the $_GET[‘Term’] and updates a certain list with those items.
function getPossibleSearches(value){
var Url = 'yourPHPFile.php?value=' + value;
var ListItem = document.getElementById('yourList');
var Contents = GetUrlOutput(Url); //you'll need to write this one yourself - use the AJAX code you can find anywhere on the net
ListItem.innerHTML = Contents;
}
try searching for different permutations of those terms
a tip- Your javascript should limit the rate at which it sends requests. People can type pretty rapidly, and that can mean a lot of rapid, potentially unnecessary requests.