
How to create AJAX with PHP
In this article, you will learn How to create AJAX with PHP.
Example:-
index.php
<html>
<head>
<title>AJAX with PHP</title>
<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", "hint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Enter name in the input field</b></p>
<form>
First name:- <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions:- <span id="txtHint"></span></p>
</body>
</html>
hint.php
<?php
$a[] = "Aman";
$a[] = "Babbu";
$a[] = "Chetna";
$a[] = "Deepak";
$a[] = "Ehsab";
$a[] = "Farhan";
$a[] = "Gurdeep";
$a[] = "Harman";
$a[] = "Inayat";
$a[] = "Jeevan";
$a[] = "Kittu";
$a[] = "Laddi";
$a[] = "Navdeep";
$a[] = "Opera";
$a[] = "Preet";
$a[] = "ram";
$a[] = "Rahul";
$a[] = "Vikram";
$q = $_REQUEST["q"];
$hint = "";
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";
}
}
}
}
echo $hint === "" ? "no suggestion" : $hint;
?>
You can Read on Facebook