Jump to content

Autocomplete in my Search engine


boba fett

Recommended Posts

I have this fully functioning search engine that I would like to add the auto complete function to.  I have an idea of what code to put (via online How-to) but my thing is I dont know where to put it in the code or if its the right type of code to do what i want.

 

<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's the code for the auto complete...

 

$(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 too...

 

 

<?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) .']');

 

 

 

 

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/207620-autocomplete-in-my-search-engine/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.