Module 3
Module 3
a) Develop AJAX application to demonstrate how a web page can communicate with a web server
while a user type characters in an input field.
FILE: AJAXex.html
<html lang="en">
<head>
<title>AJAX communication Example</title>
</head>
<body>
<h1>AJAX Live Communication With Server</h1>
<input type="text" id="input-field" placeholder="Type something...">
<div id="response">server response will appear here...</div>
<script>
document.getElementById('input-field').addEventListener('keyup',function(){
const userInput=this.value;
xhr.onload=function(){
if(xhr.status===200){
document.getElementById('response').innerHTML=xhr.responseText;
}
};
xhr.send();
});
</script>
</body>
</html>
FILE: server.php
<?php
$text=isset($_GET['text'])?$_GET['text']:'';
if(!empty($text))
{
echo "YOU TYPED:".htmlspecialchars($text);
}
else
{
echo "please type something...";
}
?>
OUTPUT:
FILE: AJAXfetch.html
<html>
<head>
<script>
function showHint(str){
if(str.length == 0) {
document.getElementById("txtHint").innerHTML="";
return;
}else{
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" +str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form action="">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
FILE: gethint.php
<?php
//Array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gundu";
$a[]="Henry";
$a[]="Ian";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tom";
$a[]="Unnie";
$a[]="Violet";
$a[]="Lisa";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wendy";
$a[]="Vicky";
//fetch q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
OUTPUT: