I've recently been doing a bit of ajax in some of my development sites. I've used exclusively PHP in the past. Almost no Javascript, which makes Ajax a little hard to understand.
What I want is an instant search box. When you type in a letter it searches for everything with that letter, and when you type in more it narrows down the results to what it can still be. The textbox you search in would be a virtual drop down box, the results being displayed under it (max of 5 or so). Each displayed result would probably be a link to go to the results.
I have a working copy of that but it only does the first result, it's the Javascript portion I'm stuck at I think. Also I haven't figued out how to do the drop down. Mine is just hacked together from a few tutorials and my little bit of know-how.
Examples are Yahoo Instant Search (although that is suggested rather than alphabetic from the database). Also the best example I found is from newegg.com, it's nice and plain and semi simple. I can add to it later.
In my PHP script:
<script type="text/javascript" language="JavaScript">
<!--
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.overrideMimeType('
text/xml')
;
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.X
MLHTTP");
}
function preSearch() {
var theQuery = document.getElementById('q
uery').val
ue;
if(theQuery !== "") {
document.getElementById('r
esult').in
nerHTML = "Searching...";
var url = 'ajax.php?q=' + theQuery;
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange
= function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('r
esult').in
nerHTML = xmlhttp.responseText + ' ';
} else {
document.getElementById('r
esult').in
nerHTML = 'Error: preSearch Failed!';
}
};
xmlhttp.send(null);
}
}
//-->
</script>
<div id="result"> </div>
Ajax.php:
if(empty($_GET['q'])) {
echo ' ';
} else {
$search = trim($_GET['q']);
$query = mysql_query("SELECT name FROM Table WHERE name LIKE '".$search."%' ORDER BY name ASC");
if(mysql_num_rows($query) == 0) {
echo 'Not Found.';
} else {
while($row = mysql_fetch_array($query) or die(mysql_error())){
echo $row['name'];
}
}
}
I'm printing out the entire resulting row, so it's the Javascript part only taking the first result I think. Not sure how to get an array (and put it in some nice dropdown) in javascript.
Thanks for any help.