Ajax is a method of using Javascript and XML to grab data from an external source or resource without having to refresh or initiate a new connection. This allows you to continuously interact with a server without the need to refresh the page. Here we are going to build a script that displays a list of suggestions to search when data is entered into an input field. For this, it would be helpful if you have at least a basic understanding of Javascript, HTML and PHP.
First, create 3 files. The names are listed below:
. ajax_framework.js (to create the Ajax connection and grab the output data)
. index.php (the location where the input field and suggestions will appear)
. suggest.php (to generate the suggestions)
Now we must add or content to the files. We will start with the main file, index.php.
Index.php
<!DOCTYPE html>
<html>
<head>
<script language=”javascript” src=”ajax_framework.js”></script>
</head>
<body>
<input type=”text” id=”q” onKeyUp=”javascript:suggest();” onKeyDown=”javascript:suggest();”>
<div id=”suggestions” style=”display:none;”>
</div>
</body>
</html>
Ajax_framework.js
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == “Microsoft Internet Explorer”){
request_type = new ActiveXObject(“Microsoft.XMLHTTP”);
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
function suggest() {
q = document.getElementById(‘q’).value;
nocache = Math.random();
http.open(‘get’, ‘suggest.php?q=’+q+’&nocache = ‘+nocache);
http.onreadystatechange = suggestReply;
http.send(null);
}
function suggestReply() {
if(http.readyState == 4){
var response = http.responseText;
s = document.getElementById(‘suggestions’);
if(response!=”"){
s.innerHTML=response;
s.style.display = “block”;
} else {
s.style.display = “none”;
}
}}
Suggest.php
<?php
$connect = mysql_connect(“localhost”, “DB_USERNAME”, “DB_PASSWORD”);
mysql_select_db(“DB_NAME”);
$searchq = strip_tags($_GET['q']);
if(strlen($searchq)>0){
$sql = ’SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE “‘.$searchq.’%” LIMIT 0,6′;
$getsql = mysql_query($sql);
while ($row = mysql_fetch_array($sql)) {
$word = $row['word'];
?>
<div onclick=”q.value=’<?php echo $word; ?>’;”>
<?php echo $word; ?>
</div>
<?php
}
}
?>
// Note: You must change the MySql connect details as well as adapt it to your database and table structure.
If you have any problems, please contact me using the contact page.