PDA

View Full Version : AJAX, how to limit result from suggestion box?



fenhopi
11-13-2010, 09:19 AM
Hi, I have this code to get hints (PHP file):


<?php

include("include/session.php");

$GetNames = "SELECT firstname, lastname, username FROM users";
$GetNamesConnect = $database->query($GetNames);

While($row = mysql_fetch_array($GetNamesConnect))
{
$a[$row['username']] = $row['firstname'] . " " . $row['lastname'];
}

//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
{
$id = $row['username'];
$response= "<a href='profile.php?user=$row['username']'>$hint</a>";

}

//output the response
echo $response;
?>


This is the display part (Javascript/Ajax)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<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>
</body>
</html>


What I want to do it to limit the names suggested to 10, how would I do this?

Dormilich
11-13-2010, 09:33 AM
LIMIT your SQL result set to 10 entries.

glenngv
11-13-2010, 09:38 AM
This is not actually a Javascript question. You need to limit the hints on the PHP side.

I'm not a PHP developer so the syntax might be wrong. But you'll get the idea.


$hint="";
$total=0;
for($i=0; $i<count($a); $i++)
{

if ($total>10) break;

if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint.", ".$a[$i];
}

$total++;

}
}
}

Edit:Looking at your code again, I think you should let SQL search for the match by adding a WHERE clause instead of searching for it manually.




//get the q parameter from URL
$q=$_GET["q"];
$GetNames = "SELECT TOP 10 firstname, lastname from users WHERE firstname like '%.$q.%' OR lastname like '%.$q.%'";

Again the PHP syntax may be wrong.

I don't know your SQL server so TOP may not be supported. You may have to change to LIMIT or something else and the syntax will be different from TOP.