AJAX PHP Examples | AJAX Code | AJAX Tutorials | Learn AJAX
×

AJAX PHP Examples

3297

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




Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments