Suggestion box in PHP

Suggestion box in PHP

Basically you type something and the software will propose suggestions

Two parts code.

The first part it’s the HTML page 


function showHint(str) {
  if (str.length==0) { 
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {

<p><b>Start typing a name in the input field below:</b></p>
First name: <input type=”text” onkeyup=”showHint(this.value)”>
<p>Suggestions: <span id=”txtHint”></span></p>



Now the PHP code to be save as gethint.php


// Fill up array with names

// get the q parameter from URL
$q=$_REQUEST[“q”]; $hint=””;

// lookup all hints from array if $q is different from “” 
if ($q !== “”) {
  $q=strtolower($q); $len=strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name,0,$len))) {
      if ($hint===””) {
      } else {
        $hint .= “, $name”;

// Output “no suggestion” if no hint were found
// or output the correct values 
echo $hint===”” ? “no suggestion” : $hint;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.