Thursday, 1 November 2012

how to save data in php using ajax and mysql

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript"  type="text/javascript">
function ajaxFunction(){
 var ajaxRequest; 

 try{
 
  ajaxRequest = new XMLHttpRequest();
 } catch (e){
 
  try{
   ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try{
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e){
   
    alert("Your browser broke!");
    return false;
   }
  }
 }

 ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){
   document.getElementById('dv').innerHTML = ajaxRequest.responseText;
  }
 }
 var eid = document.getElementById('a').value;
 var name = document.getElementById('b').value;
 var age = document.getElementById('g').value;
 var queryString = "?EID=" + eid + "&NAME=" + name+"&AGE="+age;
 ajaxRequest.open("GET", "b.php" + queryString, true);
 ajaxRequest.send(null);
}
</script>
</head>
<body>
<form name="frm" id="frm" action="#" method="post" enctype="multipart/form-data">
<table align="center">
<tr><td>EID</td><td><input type="text" name="a" id="a"  size="15" maxlength="10" /></td></tr>
<tr><td>Name</td><td><input type="text" name="b" id="b"  size="30" maxlength="50" /></td></tr>
<tr><td>Age</td><td><input type="text" name="g" id="g"  size="30" maxlength="50" /></td></tr>
<tr><td>&nbsp;</td><td><input type="button" onclick="ajaxFunction()" name="c" id="c" value="Save" style="width:80px" />&nbsp;<input type="submit" name="f" id="f" style="width:80px" value="Update" /> <input type="reset" name="d" id="d" value="Reset"  style="width:80px" /> </td></tr>
<tr><td>&nbsp;</td><td><div id="dv"></div></td></tr>
</table>
</form>
</body>
</html>
b.php page code:

<?php
$cn=mysql_connect('localhost','root','') or die('Error on connection :'.mysql_error());
$db=mysql_select_db('sankar') or die('Error on database :'.mysql_error());
$cm=mysql_query("insert into emp values('$_REQUEST[EID]','$_REQUEST[NAME]','$_REQUEST[AGE]')");
$ds=mysql_query("select * from emp");
echo "<table cellpadding='0' cellspacing='0' border='1' width='100%'><tr><th>EID</th><th>NAME</th><th>AGE</th></tr>";
while($dt=mysql_fetch_array($ds))
{
echo "<tr>". "<td>".$dt[0]."</td>"."<td>".$dt[1]."</td>"."<td>".$dt[2]."</td>"."</tr>";
}
echo "</table>";
?>

No comments:

Post a Comment