Insert Records using Ajax

free php tutorials, php classes, php utilities, free tools

In this tutorial, we will make an application, how we can insert records in a sql table using php/ajax

First we will write ajax code

<script type="text/javascript">
function ajaxFunction(name, gender, city, country, profession)
{
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}
else
{// code for IE6, IE5
xmlhttp=new XMLHttpRequest();

}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("my_div").innerHTML=xmlhttp.responseText;
}
}

xmlhttp.open("GET","insert-records.php?name="+name+"&gender="+gender+"&city="+city+"&country="+country+"&profession="+profession,true);
xmlhttp.send();
}

</script>

Now we will make a form

<form action="" method="get" name="frm1">
<table width="800" border="0">
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Name </td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Gender</td>
<td><select name="gender">
<option value="1" selected>Male</option>
<option value="2">Female</option>
</select></td>
</tr>
<tr>
<td>City</td> <td><input name="city" type="text" id="city" /></td>
</tr>
<tr>
<td>Country</td>
<td><input name="country" type="text" id="country" /></td>
</tr>
<tr>
<td>Profession</td>
<td><input name="profession" type="text" id="profession" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="button" name="Button" value="Insert records" onclick="ajaxFunction(frm1.name.value,frm1.gender.value,frm1.city.value, frm1.country.value,frm1.profession.value)" /></td>
</tr>
</table>
</form>
<div id="my_div"> </div>
Now we will make a file insert-records.php
<?php
include("db.php");
$name= $_GET['name'];
$gender= $_GET['gender'];
$city= $_GET['city'];
$country= $_GET['country'];
$profession= $_GET['profession'];
$query="insert into persons(name,gender,city,country,profession)
values('$name','$gender','$city','$country','$profession')";
echo $query;
mysql_query($query) or die();

echo "Record Successfully Added";
?>

Bookmark This Page