Friday, 19 August 2016

PHP Ajax : Save form Data to server database

Database Name : Tmp

Table Name : stu

Field : roll,name,city

Client Side File Code

<!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=iso-8859-1" />
<title>Girfa : Save Form Data to Server</title>
<script language="javascript">
function savedata()
{
alert(roll.value+ sname.value +city.value);
var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function()
{
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
                document.getElementById("data").innerHTML = xmlhttp.responseText;
            }
        };
var url='server.php?roll=' + roll.value + '&name=' + sname.value + '&city=' + city.value;

       xmlhttp.open("GET", url, true);
        xmlhttp.send();
}
</script>
</head>


<body>
<h1 align="center">Ajax Form Data Save Demo</h1><hr />
<div id="data">
<form>
Roll : <input type="text" id="roll" /><br />
Name : <input type="text" id="sname" /><br />
City : <input type="text" id="city" /><br />
<input type="button" value="save" onclick="savedata()" />
</form>
</div>
</body>
</html>

Server Side Code

<?php
//tmp is my database you can change argument as your server setting
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tmp";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$roll=$_REQUEST['roll'];
$name=$_REQUEST['name'];
$city=$_REQUEST['city'];
$sql="insert into stu values('$roll','$name','$city')";
if ($conn->query($sql) === TRUE)
{
   echo "New record created successfully";
} else
{
   echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Next Topic