I want to submit data through ajax to the database and after inserting data into database this data should be displayed on the file Demo.html dynamically at the last i.e., after div in my case.
Well storing data through ajax i have done but i don't know how to display this newly inserted data to Demo.html.So do guide me how to achieve this.
Below is my code.
AjaxFile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body >
<p><span id="get">Ajax response comes here</span></p>
<div id="divId">
<input type="text" name="i1" value="" /><br />
<input type="text" name="i2" value="" /><br />
<button onclick="ajaxFunction()">Click </button>
</div>
<script src="jquery-3.2.1.min.js" ></script>
<script type="text/javascript">
function ajaxFunction() {
$(function(){
var myData1 = $("input[name='i1']").val();
var myData2 = $("input[name='i2']").val();
$.ajax({
type : "post",
dataType : "text",
url : "controller.php",
data : { data1 : myData1, data2 : myData2},
success : function(msg){
document.getElementById('get').innerHTML = msg;
}
});
});
}
</script>
</body>
</html>
controller.php
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$databaseName = "mydb1";
try {
$conn = new PDO("mysql:host = $servername; dbname = $databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$conn->exec("use mydb1");
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['data1']) && isset($_POST['data2'])) {
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$statement = $conn->prepare("Insert into mytable (data1, data2) values (:data1 , :data2)");
if( $statement->execute(array("data1"=>"$data1", "data2"=>"$data2")) ) {
echo "successfully inserted";
// want to display $data1 and $data2 at the last in Demo.html just after inserting.
} else {
echo "Not successfully inserted";
}
} else {
echo "something is not set";
}
}catch(PDOException $e) {
echo "connection failed ". $e->getMessage();
}
$conn = null;
?>
Demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
body {
margin : 0;
}
#first {
width : 100%;
height : 100px;
margin : 30px auto auto auto;
border : 1px dashed black;
}
</style>
</head>
<body>
<div id="first" align="center"> I want to display newly inserted data below this div</div>
</body>
</html>