<!DOCTYPE html>
<html>
<head>
<title>PHP - AJAX and PHP</title>
</head>
<body>
<style type="text/css">
.ajax_php_font{
color:#F60;
font-weight:bold;
font-style:italic;
font-size:16px;
}
</style>
<script type="text/javascript">
function showHint(str) {
if (str.length == 0) {
document.getElementById("tut_name").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("tut_name").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "get_data.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<h4>Search your tutorial in the input field below :</h4>
<form>
Tutorial Name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Your tutorial name is : <span id="tut_name" class="ajax_php_font"></span></p>
</body>
</html>
First, check if the input field is empty (str.length == 0)
. If it is, clear the content of the tut_name placeholder and exit the function.
However, if the input field is not empty, do the following :
XMLHttpRequest
objectget_datat.php
) on the serverq
parameter is added to the url (get_datat.php?q="+str
)<?php
// Array with tutorials
$a[] = "C Language";
$a[] = "C++";
$a[] = "Bootstrap";
$a[] = "HTML5";
$a[] = "HTML";
$a[] = "CSS";
$a[] = "CSS3";
$a[] = "JAVA";
$a[] = "JavaScript";
$a[] = "jQuery";
$a[] = "PHP";
$a[] = "MySQL";
$a[] = "SQL";
$a[] = "Adv Java";
$a[] = "Python";
$a[] = "AngularJS";
$a[] = "Photoshop";
$a[] = "C#";
$a[] = "ASP.NET";
$a[] = "SAP";
$a[] = "ORACLE";
$a[] = "Wordpress";
$a[] = "Android";
$a[] = "iOS";
$a[] = "SEO";
$a[] = "Illustrator";
$a[] = "Flash";
$a[] = "Action Script";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>