How To Insert Data in Database Using Ajax With PhP

Project Demo

DATABASE CONNECTION CODE HERE (db.php):

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'test';
$conn = mysqli_connect("$host","$user","$pass","$db");
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
?>

DATABASE CONNECTION CODE HERE (action.php):

<?php
require "db.php";
$name=$_POST['txt1'];
$age=$_POST['txt2'];
$query= "INSERT INTO data(txt1, txt2) VALUES ('$name', '$age')";
$result = mysqli_query($conn,$query);
if(!$result)
{
echo "error";
}
else
{
header("location:index.php");
}
?>

HTML CODE HERE (index.php):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-md-4">
<div id="txt"></div>
<form method="post" action="#" id="frm">
<div class="form-group">
<input type="text" name="txt1" class="form-control" placeholder="Enter Your Name">
</div>
<div class="form-group">
<input type="text" name="txt2" class="form-control" placeholder="Enter Your Age">
</div>
<div class="form-group">
<input type="Submit" name="btn" id="btn" class="btn btn-primary" value="Submit">
</div>
</form>
</div>
</div>
</div>

AJAX AND JAVASCRIPT CODE HERE :

<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
(function($) {
"use strict";
$("#btn").click(function(e) {
$('#frm').validate({
rules: {
txt1: {
required: true
},
txt2:
{
required: true
}
},
messages: {
txt1: {
required: "Please fill this field"
},
txt2:
{
required: "Please fill this field"
}
}
})
$.ajax({
type: 'POST',
url: 'action.php',
data: $('#frm').serialize(), // I WANT TO ADD EXTRA DATA + SERIALIZE DATA
success: function(data){
alert("Success");
}
});
})
})(jQuery)
});
</script>

CSS CODE HERE :

<style type="text/css">
.error{
color: red;
}
</style>

Leave a Reply

Your email address will not be published. Required fields are marked *


Vivzon Web Technology is a small company, But the website is a super-innovative company in the field of development. With 3 years of experience, the website is designing and developing in Mumbai. we aim to bring client cost- Read More

Contact Us


Nallasopara West, Mumbai, India

+91-7240052638

+91-9004837569

info@vivzon.com

Copyright © 2017 vivzon. All rights reserved