I am a newbie in AJAX script and javascript. I am using AJAX to get search suggestion when the user type the first letter in the search box. But after typing the AJAX and javascript code, I could not get any suggestion coming out below the search box. I wonder if someone could help me to fix this problem?
By the way, I hope that the suggestion limit would be 5. How can I do this?
Code for index.php:
Code for suggestion.php:
Thanks in advance.
By the way, I hope that the suggestion limit would be 5. How can I do this?
Code for index.php:
Code:
<html> <head> <title> Brandon's Search Engine </title> <style type="text/css"> #suggestion { border: 1px solid black; visibility: hidden; } #suggestion a { font-size: 12pt; color: black; text-decoration: none; display: block; width: 450px; height: auto; } #suggestion a:hover { background-color: #dddddd; } </style> </head> <script type="text/javascript"> function getSuggestion(query) { var ajax; if(window.XMLHttpRequest)//for ie7+, FF, Chrome ajax = new XMLHttpRequest();//ajax object else ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous ajax.onreadystatechange = function(){ if(ajax.status == 200 && ajax.readyState == 4) { //if result are not there then don't display them if(ajax.responseText == "") document.getElementById("suggestion").style.visibility = "hidden"; else { document.getElementById("suggestion").style.visibility = "visible"; document.getElementById("suggestion").innerHTML = alert(ajax.responseText); } } } ajax.open("GET", "suggestion.php?q=<?php echo $query;?>"+q, false); ajax.send(); } </script> <body> <form method="GET" action="search.php"> <input type="hidden" name="page" value="0" /> <table align="center"> <tr> <td> <h1><center>Brandon's Search Engine</center></h1> </td> </tr> <tr> <td align="center"> <input type="text" name="q" size="90" onkeyup="getSuggestion(this.value)" autocomplete="off" /> </td> </tr> <tr> <td align="center"> <input type="submit" value="Search" /> <input type="reset" value="Clear" /> </td> </tr> </table> </form> <div id="suggestion" size="90"> </div> </body> </html>
Code:
<?php include 'connect.php'; //connect with database $query = $_GET["q"]; if($query != "") { $stmt = "SELECT * FROM searchengine WHERE title LIKE '%" . mysqli_real_escape_string($con,$query) . "%' OR link LIKE '%" . mysqli_real_escape_string($con,$query) . "%' LIMIT 0 , 10"; $result = mysqli_query($con,$stmt) or die(mysqli_error($con)); $number_of_result = mysqli_num_rows($result); if ($number_of_result > 0) { //results found here and display them while ($row = mysqli_fetch_assoc($result))//show first 10 results $title = $row["title"]; $link = $row["link"]; echo "<div id='sugg-search-result'>"; echo "<a href='$link' id='sugg-title'>" . $title . "</a>"; echo "</div>"; } } ?>
Comment