Author Topic: On the fly searching results as you type.  (Read 437 times)

Andrew

  • iPhone Application & Web Developer
  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 339
  • Karma: 9
  • PHP, MySQL, HTML, and CSS are my playground
    • View Profile
On the fly searching results as you type.
« on: July 13, 2012, 10:00:23 PM »
I have found this little bit of code vary useful and I thought I would give it to you all.

The basic idea here is that as an individual types something in an <input> text field the java script runs another php file with every keystroke and yields a result in a <div> somewhere on the page.

Its not as complicated as one might think.

This example will show you how to search an array of fruit but you can use this to display anything you want and run any php code you want. I often times use this to do LDAP and MySQL queries on the fly.

This is the javascript for the keypress feature. This needs to be on the same page as the <input> your typing into, I generally add it in the <head> section of my pages as a <script> but I am sure it would work as a separate file.

PHP Code: [Select]
<script type="text/javascript">
function 
showHint(str)
{
if (
str.length==0)
  { 
  
document.getElementById("txtHint").innerHTML="";
  return;
  }
if (
window.XMLHttpRequest)
  {
// code for IE7+, Firefox, Chrome, Opera, Safari
  
xmlhttp=new XMLHttpRequest();
  }
else
  {
// code for IE6, IE5
  
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (
xmlhttp.readyState==&& xmlhttp.status==200)
    {
    
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","search.php?search="+str,true); //this is the name of the file you are loading to actually run the search and the field you are passing to that file in this case search.php?search="some sting"
xmlhttp.send();
}
</script>


This is the actual code for the <input> field and display area. field you want to use. Notice there is no submit button, that is because every thing happens when you type not when you hit submit so it is not needed.
PHP Code: [Select]
<form method="get" action="<?php $_SERVER["PHP_SELF"] ?>">
<
center>Search:<br/><input type="text" onkeyup="showHint(this.value)" name="search" /></center>
</
form>

<
div id="txtHint"></div>

The issue with this code is if someone hits return to submit the form you end up right back at a blank page. So.. a little e if then statement and problem resolved.

PHP Code: [Select]
<?php 

if (!$_REQUEST){ // if there is nothing in the parameter fields on the URL do this.

?>

<form method="get" action="<?php $_SERVER["PHP_SELF"?>">
<center>Search:<br/><input type="text" onkeyup="showHint(this.value)" name="search" /></center>
</form>

<div id="txtHint"></div>


<?php 

} else { // if there is something in the parameter fields do this.

?>
<script type="text/javascript">
	
window.onLoad = showHint('<?php echo $_REQUEST["search"?>');
</script>

<form method="get" action="<?php $_SERVER["PHP_SELF"?>">
<center>Search:<br/><input type="text" onkeyup="showHint(this.value)" name="search" value="<?php echo $_REQUEST["search"]; ?>" /></center>
</form>

<div id="txtHint"></div>

<?php 
}
?>


Now on our second file we actually preform the search of our array.

PHP Code: [Select]
<?php
$fruit 
= array("apple","orange","grape","tomato","cherry","watermelon"); // this is our array

foreach ($fruit as $key => $value) { // this does just what it says it does.. for every value in the array take the key and out put the value as a variable $value
	
$pos strpos($value$_REQUEST['search']); // This searches every value in the array for a series of letters that matches what you typed 
	
if (
$pos === false) { // if no results exists do nothing
        
} else {
	
	
echo 
$value."<br/>";
	
}
}

?>


and there you have it an array searched on the fly by the letters in the individual words in the array.

Here are the two files completed.

index.php:
PHP Code: [Select]
<script type="text/javascript">
function 
showHint(str)
{
if (
str.length==0)
  { 
  
document.getElementById("txtHint").innerHTML="";
  return;
  }
if (
window.XMLHttpRequest)
  {
// code for IE7+, Firefox, Chrome, Opera, Safari
  
xmlhttp=new XMLHttpRequest();
  }
else
  {
// code for IE6, IE5
  
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (
xmlhttp.readyState==&& xmlhttp.status==200)
    {
    
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","search.php?search="+str,true);
xmlhttp.send();
}
</script>


<?php 

if (!$_REQUEST){ // if there is nothing in the parameter fields on the URL do this.

?>

<form method="get" action="<?php $_SERVER["PHP_SELF"?>">
<center>Search:<br/><input type="text" onkeyup="showHint(this.value)" name="search" /></center>
</form>

<div id="txtHint"></div>


<?php 

} else { // if there is something in the parameter fields do this.

?>
<script type="text/javascript">
	
window.onLoad = showHint('<?php echo $_REQUEST["search"?>');
</script>

<form method="get" action="<?php $_SERVER["PHP_SELF"?>">
<center>Search:<br/><input type="text" onkeyup="showHint(this.value)" name="search" value="<?php echo $_REQUEST["search"]; ?>" /></center>
</form>

<div id="txtHint"></div>

<?php 
}
?>

search.php:
PHP Code: [Select]
<?php
$fruit 
= array("apple","orange","grape","tomato","cherry","watermelon");

foreach (
$fruit as $key => $value) {
	
$pos strpos($value$_REQUEST['search']);
	
if (
$pos === false) {
	
} else {
	
	
echo 
$value."<br/>";
	
}
}

?>
You cannot solve a puzzle if you don't have all the pieces.
Please + my karma if I helped you. <-- over there under my picture.

GunMuse

  • New Member
  • *
  • Posts: 16
  • Karma: 0
    • View Profile
Re: On the fly searching results as you type.
« Reply #1 on: November 19, 2012, 09:55:30 AM »
I saw you link to this when somene asked for search.  These are neat User features but I would like to warn that this in a production enviorment would cause massive uneccary searchs.  Fill the mysql Cache with worthless partial word searches and slow down the overall site as well as the search function.

Some cleanups would be to run a seperate Sql call and make sure you tag it Sql NOCACHE. 
Also don't start your search looping until you reach 3 letters typed.  Theres no indexing below that anyway.
Also place in your page somewhere NOT to bring up this feature becuase many users are disabling javascript these days because of virus injection from webads via Flash.
Finally I would shorten and seperate the list to Previously searched for keywords that you generate and HARD FILE that list daily.   Let the buffers of an array under 4 mb bring back your speed.  I see your example of the fruit but realisically many coders try to dump a Mysql query into that array.

Andrew

  • iPhone Application & Web Developer
  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 339
  • Karma: 9
  • PHP, MySQL, HTML, and CSS are my playground
    • View Profile
Re: On the fly searching results as you type.
« Reply #2 on: November 21, 2012, 03:39:17 PM »
I use this method on many live sites and it works very well. With SQL queries as well as LDAP queries. It has not caused site slowdowns and I have not had cacheing issues. You are more than welcome to look at the live versions if you would like

degrees.utah.edu
gradschool.utah.edu/centers
You cannot solve a puzzle if you don't have all the pieces.
Please + my karma if I helped you. <-- over there under my picture.

GunMuse

  • New Member
  • *
  • Posts: 16
  • Karma: 0
    • View Profile
Re: On the fly searching results as you type.
« Reply #3 on: November 24, 2012, 09:50:46 PM »
Your not looking through 2gig + of data from what I can see.  Small Db's can use this feature with ease was not trying to say NEVER use it just don't hang fuzzy dice on a tank mirror:)