Find a user
Okay this is a tutorial showing you how to create your own ajax search script. Okay first lets create the search page.
I will be calling this page
search.php
seach.php
Code
<?
require_once "config.php"; //REQUIRE ONCE FOR SECURITY PURPOSES
$userid= $_SESSION['id'];
$getuser= mysql_query("SELECT * FROM `members` WHERE `id`='$userid'");
//GET USER INFO FROM DB
//NOW FOR REST OF SEARCH PAGE
?>
<html><head><title>Your title</title>
<script src="forms-search.js"></script>
<? //BECAME LAZY FOR ALL THOSE PPL WHO WANT TO INTEGRATE THIS SCRIPT INTO THEIR SITE :) ?>
</head>
<body>
<div align=center><br /><br />
<input type=text style="background-color:#FFFFFF; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;" name=search-username onkeypress="search(this.value);" /><br /><hr />
<strong>
<div id=txtHint> </div>
<? //IM USING A ID IM USED TO. UNLESS YOU WANT TO CHANGE SOME STUFF IN THE 'forms-search.php' SCRIPT THEN I RECOMMEND LEAVING THIS ALONE. ?>
</strong>
</div>
</body>
</html>
Yeh smaller than my other tutorial. This code will be easier to interegrate into your site.
Okay now we need to code the javascript ajax page called
forms-search.js. Heres the code for it...
forms-search.js
Code
var xmlHttp
function search(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="search2.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Wow. I dont expect u to remember the above code. In fact i just copied and pasted it from a page in my server. Okay now that this page is done we now need to code one more page. We will call this page
search2.php Heres the coding for it...
search2.php
Code
<?php
$q= $_GET["q"];
require_once "config.php";
$sql="SELECT * FROM `members` WHERE username LIKE '%$q%'";
$result = mysql_query($sql);
$check= mysql_num_rows($result);
if ($check == "0" || !isset($q)){
echo "NO SUCH USER WAS FOUND!";
}else{
echo "<table border='1' bordercolor=black frame=box rules=all cellpadding=0 cellspacing=0 align=center bgcolor=#333333 width=100%>
<tr bgcolor=red>
<th><div align=center>USERNAME</strong></div></th>
</tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
$usersname= $row['username'];
echo "<td><div align=center>$usersname</div></td>";
echo "</tr>";
}
echo "</table>";
}
?>
Okay now your done. Save all your pages and if youve followed (or copied and pasted ;) ) correctly then you shud have a nice ajax search script.