I am using php, MySQL, and Ajax. When I submit the form data is not stored in the database table. But when put action="insert.php" data is submitted to the database table but the page gets refreshed. I am badly stuck here. Can anyone please advice me that how can I solve this problem?? Thanks in advance guys. codes are given below :
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="cForm" name="cForm" method="post">
<label>Roll No : </label>
<input type="text" name="roll" id="roll"><br>
<label>Name : </label>
<input type="text" name="name" id="name"><br>
<label>Stream : </label>
<select name="stream" id="stream">
<option value="CSE">CSE</option>
<option value="IT">IT</option>
<option value="ECE">ECE</option>
<option value="ME">ME</option>
</select><br>
<label>Age : </label>
<input type="text" name="age" id="age"><br>
<input type="submit" name="submit" value="Submit">
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#cForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url:"insert.php",
method:"POST",
data:$('#cForm').serialize(),
success:function(data)
{
if(data == 'ok')
{
document.getElementById("cForm").reset();
}
}
});
});
});
</script>
</div>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("localhost","root","","test");
if(isset($_POST['submit'])){
$roll=$_POST['roll'];
$name=$_POST['name'];
$stream=$_POST['stream'];
$age=$_POST['age'];
$sql="INSERT INTO `student`(`name`, `stream`, `age`) VALUES ('$name','$stream','$age')";
$result=mysqli_query($con,$sql);
if(isset($result))
{
echo 'ok';
}
}
?>