So I have built a little search engine which scans my SQL databases. As opposed to having it reload a new page, I'd like to know how I could load my results ont he same page via AJAX. The following is the search.html and search.php code I use for displaying the search results now. How would I go about containing this and displaying the results in a single page, updating the results with AJAX? search.html <html> <body> <form name="form" action="search.php" method="get"> <input type="text" name="q" /> <input type="submit" name="Submit" value="Search" /> </form> </body> </html> Code (markup): search.php <?php $var = @$_GET['q'] ; $trimmed = trim($var); $limit=10; mysql_connect("localhost","user","pass"); mysql_select_db("sql_database") or die("Unable to select database"); $query = "SELECT * FROM Users WHERE FirstName='$var' ORDER BY LastName DESC"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); echo "Results <br /><br />"; $count = 1 + $s ; while ($row= mysql_fetch_array($result)) { echo "$count.) " . $row["FirstName"] . " " . $row["LastName"] . "<br />" ; $count++ ; } $currPage = (($s/$limit) + 1); echo "<br />"; if ($s>=1) { $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } $pages=intval($numrows/$limit); if ($numrows%$limit) { $pages++; } if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> Code (markup):
Mate, if you can write a search script you should have no trouble with AJAX Your only choice really is do you want to use plain Javascript, or do it the easy way with a framework, like jQuery or Prototype? There are heaps of tutorials for both options. This is another nice jQuery one: Nettuts - Submit A Form Without Page Refresh using jQuery And this one will show you how much work you save by using a framework: WebReference - How To Create Form Posts with Ajax
Something like: <form name="form" action="search.php" method="get"> <input type="text" name="q" id="q" /> <input type="submit" name="Submit" value="Search" id="btnSearch" /> </form> <div id="results"></div> <script type="text/javascript"> document.getElementById("btnSearch").onclick = function() { var q = document.getElementById("q").value; loadurl("search.php","&q=" + q,"results"); return false; } function loadurl(url,query,divid) { if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById(divid).innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET",url + "?t=" + Math.random() + query,true); xmlhttp.send(); } </script> Code (markup):