Know Your Age through AJAX and PHP [Free Source code]

In this tutorial, I will guide you how to develop a small web application that shows users age when he enters his year of birth. The calculation happens in real time without page refresh using Ajax.
The application takes Date of Birth as an input, processes it and displays the age to the user.

Overview

Further, You will need to save the following file and keep them in the same folder.

  • Getage.php
  • Index.html
  • Getage.php

The file contains the code that will read the URL, that is generated when users input his year of birth, with the GET method.
Then, that year will be deducted from present time in order to get the difference and, that result will be sent back to the user using PHP echo keyword as his current age.

<?php
$yob=$_GET[‘YoB’];

$age=date(“Y”)-$yob;

if($age==0)
{
echo “YOUR AGE:<input type=text value=$age readonly size=3><br>”;
echo ‘<br><b><font face=cambria color=#ff1493>Hello Baby!!<br>’;
}
else if($age<0)
{

echo “<br><font color=#a52a2a>You haven’t born yet!!</b> “;
}
else
{
echo “Age ::<input type=text value=$age readonly size=3><br>”;
echo “<br><font color=#000099>Congratulations! Your are <b> “.$age.” years</b> old”;
}
?>

Index.html

In this page, the codes will render the HTML form which is used by the user to enter his/her year of birth. After that as soon as the user enters it, a JS method call hint fill fire and it will read the year.
If it is valid it will make a call to back end embedding data in the URL.

<html>
<head>
<title>Tutorial-28</title>
<script type=”text/javascript”>
function hint(string)
{
if(string.length==0)
{
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if(window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”getage.php?YoB=”+string,true);
xmlhttp.send();
}
</script>
</head>
<body>
<center>
<form method=”GET”>
<span>Year of Birth :: </span><input type=”text” onkeyup=”hint(this.value)” size=”20″/>
</form>
<p>Age Is Shown Below<div id=”txtHint”></div></p>
</center>
</body>
</html>

Bonus:

You can download the complete working demo source code here:

I hope the tutorial helped you to learn how to display the age of user using Ajax, HTML, and PHP.
I would love to solve your problem if any so don’t forget to comment. Also, appreciate if you shared the post with your friends.

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

Leave a Reply

Your email address will not be published. Required fields are marked *