Ajax Example

In this example we create two files
(1) is index.php, which is client side file.
(2) is ajax_results.php, which is server side file.

You can download code from this url

rar_image

In index.php file

<html>
	<head>
		<script>
						function Ajaxfun(){
			var ajaxRequest; // The variable that makes Ajax possible!
			try{
			// Opera 8.0+, Firefox, Safari
			ajaxRequest = new XMLHttpRequest();
			}catch (e){
			// Internet Explorer Browsers
			try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
			}catch (e) {
			try{
			ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}catch (e){
			// Something went wrong
			alert("Your browser broke!");
			return false;
			}
			}
			}

			// Now get the value from user name, user sex and pass it to
			// server script.
			var uname = document.getElementById('uname').value;
			var usex = document.getElementById('usex').value;

			var queryString = "?uname=" + uname ;
			queryString += "&usex=" + usex;
			ajaxRequest.open("GET", "ajax-results.php" + queryString, true);
			ajaxRequest.send(null);

			// Create a function that will receive data
			// sent from the server and will show data on the ajax div.
			ajaxRequest.onreadystatechange = function(){
			if(ajaxRequest.readyState == 4){
			var ajaxDisplay = document.getElementById(‘ajaxDiv’);
			ajaxDisplay.innerHTML = ajaxRequest.responseText;
			}
			}

			}</script>
	</head>
	<body>
		<form>
			<div>
				<div style="float: left;width:30%">
					Your Name
				</div>
				<div style="float: left;width:70%">
					<input type="text" id="uname" />
				</div>
			</div>
			<div>
				<div style="float: left;width:30%">
					Your Sex
				</div>
				<div style="float: left;width:70%">
					<select name="usex" id="usex">
						<option value="">Select</option>
						<option value="male">Male</option>
						<option value="female">Female</option>
					</select>
				</div>
			</div>
			<div style="clear: both"></div>
			<div align="center" onClick="Ajaxfun()">
				<span style="background-color:#3a5795; color:#fff; cursor: pointer;">Get</span>
			</div>
			<div style="clear: both"></div>
			<div id="ajaxDiv"></div>
		</form>
	</body>
</html>

In ajax_request.php

<?php
$uname=$_REQUEST['uname'];
$usex=$_REQUEST['usex'];
$errmsg="";
$err_count=0;
if($uname=='')
{
$errmsg .="Please write the name";
$err_count++;
}
if($usex =='')
{
$errmsg .="Please select the sex";
$err_count++;
}
if($err_count==0)
{
echo "Hi, your name is $uname and sex is $usex";
}else{
echo $errmsg;
}
?>

Output is:-
ajax_output