Home >>Ajax Tutorial >Ajax Post Method Example

Ajax Post Method Example using JavaScript

AJAX Post Method example

 

Registration Page

<DoctypeHtml>
<html>
	<head>
		<title>Registration form</title>
		<script src="java.js" rel="javascript"></script>
	</head>
	<body>
		<form>
			<table align="center">
				<tr>
					<th colspan="2">Registration form</th>
				</tr>
				<tr>
					<td colspan="2"><span id="msg"></span></td>
				</tr>
				<tr>
					<th>Name</th>
					<td><input type="text" id="n" placeholder="eg; John"></td>
				</tr>
				<tr>
					<th>Email</th>
					<td><input type="email" id="e" placeholder="eg:[email protected]"></td>
				</tr>
				<tr>
					<th>Mobile</th>
					<td><input type="number" id="m"placeholder="+91-1234567890"></td>
				</tr>
				<tr>
					<th>Address</th>
					<td><textarea id="ad" placeholder="eg:b/12 abc new delhi-110023"></textarea></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" onClick="savedata()">  
					<input type="reset"></td>
				</tr>
			</table>
		</form>
	</body>
</html>

 

JavaScript Function(Send Request to Server and get Response)

// creating method for passing data via using post method
function savedata()
{
			
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("msg").innerHTML=xmlhttp.responseText;
		alert(xmlhttp.responseText);
		}
	}
		
	var n=document.getElementById("n").value;
	var e=document.getElementById("e").value;
	var p=document.getElementById("m").value;
	var ad=document.getElementById("ad").value;

	//alert(e);
	var url="insert.php";
	var par="name="+n+"&email="+e+"&mobile="+p+"&add="+ad;
	//var t=typeof(parameter);
	//alert(par);
	
	xmlhttp.open("POST",url,true);
	
	xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("content-length",par.length);
	xmlhttp.setRequestHeader("connection","close");

	xmlhttp.send(par);

}

 

PHP Page for Receiving Data From AJax(JavaScript Page)

<?php
//create your database and table then connect 
$con=mysqli_connect("localhost","root","","ajaxpost");

$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$mob=$_REQUEST['mobile'];
$add=$_REQUEST['add'];

if(mysqli_query($con,"insert into registration values('','$name','$email','$mob','$add')"))
echo "Data Saved";

?>

No Sidebar ads