High guyz am tryin to get hint from my database but i am managing to do so,though if i list the array am able. please help if any one has an idea

here is the html code

<html>
<head>
<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==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head
<body>

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

</body>
</html>

and the php code looks like this

<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
  {
  $hint="";
  for($i=0; $i<count($a); $i++)
    {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
      {
      if ($hint=="")
        {
        $hint=$a[$i];
        }
      else
        {
        $hint=$hint." , ".$a[$i];
        }
      }
    }
  }

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
  {
  $response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response
echo $response;
?>

Dani AI

Generated

Quick, practical update for future readers. started with the W3Schools XHR example and later moved names into a database per ; suggested using a library. The common pitfalls shown in the thread are: unchecked DB calls that can fail, returning plain HTML text that invites injection, and hammering the server with every keystroke. The clean, robust pattern is: use a modern DB API with prepared statements, return JSON, throttle requests client-side, and avoid inserting unescaped HTML.

Server-side (PHP, PDO): return a JSON array of suggestions and set an appropriate header. Use a prepared LIKE query with a LIMIT and explicit charset. Example:

<?php
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($q === '') { echo json_encode([]); exit; }

try {
    $pdo = new PDO('mysql:host=DB_HOST;dbname=DB_NAME;charset=utf8mb4', 'DB_USER', 'DB_PASS', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    $stmt = $pdo->prepare('SELECT name FROM products WHERE name LIKE :p ORDER BY product_code LIMIT 10');
    $stmt->execute([':p' => $q . '%']);
    $names = $stmt->fetchAll(PDO::FETCH_COLUMN);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($names);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([]);
    // log $e->getMessage() to server logs
}

Client-side: debounce input, require a minimum length, use encodeURIComponent and parse JSON; insert text nodes (not raw HTML) to avoid XSS.

// minimal debounce + fetch example
let timer;
input.addEventListener('input', () => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    const q = input.value.trim();
    if (q.length < 2) { showEmpty(); return; }
    fetch('gethint.php?q=' + encodeURIComponent(q))
      .then(r => r.json())
      .then(list => renderList(list))
      .catch(console.error);
  }, 250);
});

Troubleshooting tips: enable error reporting on dev, check server logs and the browser Network tab, validate that your DB connection and SQL are correct (a failed query returns false), and prefer prepared statements (security and stability). This approach addresses the thread issues while making the solution safe and maintainable.

Recommended Answers

All 6 Replies

hehe your ajax example is from w3schools...

ok first make a database for names, then query them all

then changed this part from an array

// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

to

$sql = mysql_query("SELECT name FROM users"); //sample table users
while($row=mysql_fetch_array($sql)){
$a[] = $row['name'];
}

First of all please rephrase your question.

Secondly, I recommend to use jQuery instead of reinventing the wheel again in using ajax.

Thirdly, i believe that w3schools ajax code is not correct since it was not working with me under some circumstances. Change the line 27 from

xmlhttp.send(); to xmlhttp.send(NULL);

thanx the code worked...and yes code is from W3schools.
the code for w3schools works alright but you need to understand it, in this case if you changed the last part of the code

xmlhttp.send();

to

xmlhttp.send(arguments);

it will work under all circumstances..thanx anyway

tha code worked for a few minutes when i came back it gave me the following error:
mysql_fetch_array() expects parameter 1 to be resource, boolean. the warning is shown at the following line

while($row=mysql_fetch_array($query, $db) or die(mysql_error))

just stick to my original code and you'll do fine

$sql = mysql_query("SELECT name FROM users"); //sample table users
while($row=mysql_fetch_array($sql)){
$a[] = $row['name'];
}

thanx ur code helped me alot tho it didn't work as surposed so i changed some part of code and it worked..i changed it to

$query = 'SELECT name FROM ecomm_products ORDER BY product_code';
$result= mysql_query($query, $db) or die(mysql_error($db));
while($row =mysql_fetch_assoc($result)){
    foreach($row as $value){
     $a[] = $row['name'];
    }
}

thanx anyway

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.