Page 1 of 1

Autocomplete in my Search engine

Posted: Tue Jul 13, 2010 10:48 am
by boba fett
I have a functioning search engine and would like to add the auto complete feature to it. I have an idea of what code to put in (via online How-to) but i have no clue where to put it.


<HTML>
<title>Snakebook Search Engine</title>
<link href="CSS/redandblack.css" rel="stylesheet" type="text/css">
<form action='search.php' method='GET'>
<font face='sans-serif' size='5'>
<center>
<p><img src="images/Snakebook-Logo.png" width="311" height="83" /><br />
<input type='text' size='50' name='search' />
</p>
<p>
<input type='submit' name='submit' value='Search' />
<br />
</p>
</center>
</font>

</form>
</HTML>



<?php
mysql_free_result($specieslist);


//get data
$button = $_GET['submit'];
$search = $_GET['search'];

if (!$button)
echo "You didn't submit a keyword.";
else
{
if (strlen($search)<=2)

echo "Search not valid. Search term too short.";
else
{
echo "You searched for <b>$search</b> <hr size='1'>";

//connect to our database
mysql_connect("localhost:8889","root","root");
mysql_select_db("snakebook");


{
//explode our search term
$search_exploded = explode(" ",$search);

foreach($search_exploded as $search_each)
{

//construct query
$x++;
if ($x==1)
$construct .="Scientific_Name LIKE '%$search_each%'
OR Common_Name LIKE '%$search_each%'
OR Physical_Characteristics LIKE '%$search_each%'
OR Geographic_Range LIKE '%$search_each%'
OR Diet LIKE '%$search_each%'
OR Venom LIKE '%$search_each%'
OR Habitat LIKE '%$search_each%'
OR Notes LIKE '%$search_each%'
";

else
$construct .=" OR Scientific_Name '%$search_each%'
OR Common_Name LIKE '%$search_each%'
OR Physical_Characteristics LIKE '%$search_each%'
OR Geographic_Range LIKE '%$search_each%'
OR Diet LIKE '%$search_each%'
OR Venom LIKE '%$search_each%'
OR Habitat LIKE '%$search_each%'
OR Notes LIKE '%$search_each%'
";


}

//echo out construct

$construct = "SELECT * FROM specieslist WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);


if ($foundnum==0)
echo "No results found.";
else
{

echo "<b>$foundnum</b> result(s) found.<p><hr size='1'>";

while ($runrows = mysql_fetch_assoc($run))


{
//get data to display

echo "<center><table border='0' cellpadding='5' cellspacing='0'>
"
;


$common = $runrows['Common_Name'];
$scientific = $runrows['Scientific_Name'];
$thumbnail = $runrows['Thumbnail'];


//display data


echo "<tr>
<td><strong>$thumbnail</strong></td>
<td><strong><i>$scientific</i></strong></td>
<td><strong>$common</strong></td>
<td><strong>$view</strong></td>
</tr>";


}

}
}

}

}
?>



here is the code for the autocomplete...

$(document).ready(function() {

//Checking for the selected Item and handling it in
//autocompletion list.
var selectedItem = null;
var setSelectedItem = function(item) {
selectedItem = item;
if (selectedItem === null) {
$autocomplete.hide();
return;
}
if (selectedItem < 0) {
selectedItem = 0;
}
if (selectedItem >= $autocomplete.find('li').length) {
selectedItem = $autocomplete.find('li').length - 1;
}
$autocomplete.find('li').removeClass('selected')
.eq(selectedItem).addClass('selected');
$autocomplete.show();
};

var populateSearchField = function() {
$('#content').val($autocomplete.find('li').eq(selectedItem).text());
setSelectedItem(null);
};

//Handling user events.
$('#content').keypress(function(event) {
if ((event.keyCode == 13) && selectedItem !== null) {
// User pressed enter key.
populateSearchField();
event.preventDefault();
}
});

//Making sure that default autocomplete of browser off.
$('#content').attr('autocomplete', 'off');
var $autocomplete = $('<ul class="autocomplete"></ul>').hide().insertAfter('#content');

//Ajax retrieval of the data from the database using PHP.
//Here the code is shown in gethint.php
$('#content').keyup(function() {
if (event.keyCode > 40 || event.keyCode == 8) {
$.ajax({
'url': 'gethint.php',
'data': {'hint': $('#content').val()},
'dataType': 'json',
'type': 'GET',
'success': function(data) {
if (data.length) {
$autocomplete.empty();
//Appending the suggestions to the list
$.each(data, function(index, term) {
$('<li></li>').text(term).appendTo($autocomplete)
.mouseover(function() { //Handling mouse over event.
setSelectedItem(index);
})
.click(function() { //Handling mouse click event.
$('#content').val(term);
$autocomplete.hide();
});
});
setSelectedItem(0);
}
else {
setSelectedItem(null);
}
}
});
}
else if (event.keyCode == 38 && selectedItem !== null) {
// User pressed up arrow
setSelectedItem(selectedItem - 1);
event.preventDefault();
}
else if (event.keyCode == 40 && selectedItem !== null) {
// User pressed down arrow.
setSelectedItem(selectedItem + 1);
event.preventDefault();
}
else if (event.keyCode == 27 && selectedItem !== null) {
//User pressed escape key.
event.preventDefault();
}
});
//Make sures that it removes the list when textbox looses focus
$('#content').blur(function(event) {
setSelectedItem(null);
});
});



and this...

<?php

//Checking whether the passed string is empty
if (strlen($_REQUEST['hint']) < 1) {
print '[]';
exit;
}

//Connecting to database
$link = mysql_connect('localhost','root','password') or die("Could not connect now");
mysql_select_db("databasename") or die("Database not found");

//Select the table from which you want to retrieve the data.
//Here tablename => pde and columnName => item_name. Use your own.
$data = mysql_query("select distinct(item_name) as 'item_name' from pde");
$i=0;
while($row = mysql_fetch_assoc($data))
{
$a[$i++]= $row['item_name'];
}


$possibilities = array();
foreach ($a as $term) {
if (strpos(strtolower($term), strtolower($_REQUEST['hint']))=== 0) {
$possibilities[] = "'". str_replace("'", "\\'", $term)."'";
}
}
print ('['. implode(', ', $possibilities) .']');

Re: Autocomplete in my Search engine

Posted: Tue Jul 13, 2010 11:44 am
by Jade
You need to put the javascript in some kind of .js file and then include it at the top of the page so you'll end up having 4 files total. Also you'll need to include the jQuery library.

Here's your autocomplete.js file:
[text]

$(document).ready(function() {

//Checking for the selected Item and handling it in
//autocompletion list.
var selectedItem = null;
var setSelectedItem = function(item) {
selectedItem = item;
if (selectedItem === null) {
$autocomplete.hide();
return;
}
if (selectedItem < 0) {
selectedItem = 0;
}
if (selectedItem >= $autocomplete.find('li').length) {
selectedItem = $autocomplete.find('li').length - 1;
}
$autocomplete.find('li').removeClass('selected')
.eq(selectedItem).addClass('selected');
$autocomplete.show();
};

var populateSearchField = function() {
$('#content').val($autocomplete.find('li').eq(selectedItem).text());
setSelectedItem(null);
};

//Handling user events.
$('#content').keypress(function(event) {
if ((event.keyCode == 13) && selectedItem !== null) {
// User pressed enter key.
populateSearchField();
event.preventDefault();
}
});

//Making sure that default autocomplete of browser off.
$('#content').attr('autocomplete', 'off');
var $autocomplete = $('<ul class="autocomplete"></ul>').hide().insertAfter('#content');

//Ajax retrieval of the data from the database using PHP.
//Here the code is shown in gethint.php
$('#content').keyup(function() {
if (event.keyCode > 40 || event.keyCode == 8) {
$.ajax({
'url': 'gethint.php',
'data': {'hint': $('#content').val()},
'dataType': 'json',
'type': 'GET',
'success': function(data) {
if (data.length) {
$autocomplete.empty();
//Appending the suggestions to the list
$.each(data, function(index, term) {
$('<li></li>').text(term).appendTo($autocomplete)
.mouseover(function() { //Handling mouse over event.
setSelectedItem(index);
})
.click(function() { //Handling mouse click event.
$('#content').val(term);
$autocomplete.hide();
});
});
setSelectedItem(0);
}
else {
setSelectedItem(null);
}
}
});
}
else if (event.keyCode == 38 && selectedItem !== null) {
// User pressed up arrow
setSelectedItem(selectedItem - 1);
event.preventDefault();
}
else if (event.keyCode == 40 && selectedItem !== null) {
// User pressed down arrow.
setSelectedItem(selectedItem + 1);
event.preventDefault();
}
else if (event.keyCode == 27 && selectedItem !== null) {
//User pressed escape key.
event.preventDefault();
}
});
//Make sures that it removes the list when textbox looses focus
$('#content').blur(function(event) {
setSelectedItem(null);
});
});
[/text]


Here's your formsearch.php file:

Code: Select all

<HTML>
<head>
<title>Snakebook Search Engine</title>
<link href="CSS/redandblack.css" rel="stylesheet" type="text/css">
<script src="http://jquery.com/src/jquery-latest.js"></script> <!-- the jquery library -->
<script src="autocomplete.js"></script> <!-- your js scripts -->
</head>
<body>
<form action='search.php' method='GET'>
<font face='sans-serif' size='5'>
<center>
<p><img src="images/Snakebook-Logo.png" width="311" height="83" />

<input type='text' size='50' name='search' />
</p>
<p>
<input type='submit' name='submit' value='Search' />

</p>
</center>
</font>
</form>
</body>
</HTML>
Here's your search.php file (where searchform posts to):

Code: Select all

<?php
mysql_free_result($specieslist);


//get data
$button = $_GET['submit'];
$search = $_GET['search'];

if (!$button)
echo "You didn't submit a keyword.";
else
{
if (strlen($search)<=2)

echo "Search not valid. Search term too short.";
else
{
echo "You searched for <b>$search</b> <hr size='1'>";

//connect to our database
mysql_connect("localhost:8889","root","root");
mysql_select_db("snakebook");


{
//explode our search term
$search_exploded = explode(" ",$search);

foreach($search_exploded as $search_each)
{

//construct query
$x++;
if ($x==1)
$construct .="Scientific_Name LIKE '%$search_each%'
OR Common_Name LIKE '%$search_each%'
OR Physical_Characteristics LIKE '%$search_each%'
OR Geographic_Range LIKE '%$search_each%'
OR Diet LIKE '%$search_each%'
OR Venom LIKE '%$search_each%'
OR Habitat LIKE '%$search_each%'
OR Notes LIKE '%$search_each%'
";

else
$construct .=" OR Scientific_Name '%$search_each%'
OR Common_Name LIKE '%$search_each%'
OR Physical_Characteristics LIKE '%$search_each%'
OR Geographic_Range LIKE '%$search_each%'
OR Diet LIKE '%$search_each%'
OR Venom LIKE '%$search_each%'
OR Habitat LIKE '%$search_each%'
OR Notes LIKE '%$search_each%'
";


}

//echo out construct

$construct = "SELECT * FROM specieslist WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);


if ($foundnum==0)
echo "No results found.";
else
{

echo "<b>$foundnum</b> result(s) found.<p><hr size='1'>";

while ($runrows = mysql_fetch_assoc($run))


{
//get data to display

echo "<center><table border='0' cellpadding='5' cellspacing='0'>
"
;


$common = $runrows['Common_Name'];
$scientific = $runrows['Scientific_Name'];
$thumbnail = $runrows['Thumbnail'];


//display data


echo "<tr>
<td><strong>$thumbnail</strong></td>
<td><strong><i>$scientific</i></strong></td>
<td><strong>$common</strong></td>
<td><strong>$view</strong></td>
</tr>";


}

}
}

}

}
?>
Here's what generates the auto complete search results, file gethint.php:

Code: Select all

//Checking whether the passed string is empty
if (strlen($_REQUEST['hint']) < 1) {
print '[]';
exit;
}

//Connecting to database
$link = mysql_connect('localhost','root','password') or die("Could not connect now");
mysql_select_db("databasename") or die("Database not found");

//Select the table from which you want to retrieve the data.
//Here tablename => pde and columnName => item_name. Use your own.
$data = mysql_query("select distinct(item_name) as 'item_name' from pde");
$i=0;
while($row = mysql_fetch_assoc($data))
{
$a[$i++]= $row['item_name'];
}


$possibilities = array();
foreach ($a as $term) {
if (strpos(strtolower($term), strtolower($_REQUEST['hint']))=== 0) {
$possibilities[] = "'". str_replace("'", "\\'", $term)."'";
}
}
print ('['. implode(', ', $possibilities) .']');

Re: Autocomplete in my Search engine

Posted: Tue Jul 13, 2010 2:41 pm
by boba fett
Great! Thank you so much! But what do you mean by jquery library and where would it go?? What would I need to do with the jquery library to include in the code??

Re: Autocomplete in my Search engine

Posted: Tue Jul 20, 2010 11:00 am
by Jade
The code below is using the jQuery library's syntax and functions. You can read more about jQuery and view some tutorials here: http://jquery.com/

[text]$('#content').val($autocomplete.find('li').eq(selectedItem).text());[/text]