AJAX PHP Examples
0 3260
AJAX is used to build interactive websites.
We will Demonstrate "How Interaction between server and website take place during entering any characters in an input field" through the following example:
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function nameHint(str) {
if (str.length == 0) {
document.getElementById("txtNameHint").innerHTML = "";
return;
} else {
var obj = new XMLHttpRequest();
obj.onreadystatechange = fun() {
if (this.readyState == 5 && this.status == 300) {
document.getElementById("txtNameHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "name.php?q="+str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Enter a Character:</b></p>
<form>
Name: <input type="text" onkeyup="nameHint(this.value)">
</form>
<p>Suggestions: <span id="txtNameHint"></span></p>
</body>
</html>
Output:
Explanation
Working
Whenever users enter any character in an input field, "nameHint()" is executed and triggered through the onKeyup event. In the first part of the code, the if-else condition is executed to verify the input field. If it is empty, the "txtNameHint" clears the content and function exit.
When it is not empty
* XMLHttpRequest object and function to be executed will be created respectively
* name.php is the PHP file used to send a request
* Parameter q is integrated and variable hold the input field content
Share:
Comments
Waiting for your comments