Hello friends in this web tutorial we are going to discuss how can we insert data into mysql table through Bootstrap Modal by using php script with Ajax jquery without page refresh. In previous tutorial on Bootstrap Modal we have show dynamic data from database to Bootstrap Modal by using PHP with Ajax jquery. Bootstrap Modal is a pop up or dialog box that appeared on top of the web page. Bootstrap Modal is used from displaying dynamic data from database to pop dialog box, in Bootstrap Modal we can also create form also, so we can also use Bootstrap Modal for inserting or updating of database data also. By using this plugin we can insert or fetch data without open new page, but we can do on page without opening of new web page. This is the modern concept of insert data through Bootstrap Modal by using Ajax request method and it has been send request to php script and php script has clean data and insert into mysql table and after inserting data success fully then after we want to show inserted on web page, in php script we have fetch data from mysql table and send back data to ajax request method in html form. And by using jquery code we have display that html data on web page. This all process has been done without page refresh event. By using Bootstrap Modal we have done all type of crud operation by using Ajax with Jquery and PHP.
Source Code
index.php
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM employee ORDER BY id DESC";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Bootstrap Modal with Dynamic MySQL Data using Ajax & PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:700px;">
<h3 align="center">Insert Data Through Bootstrap Modal by using Ajax PHP</h3>
<br />
<div class="table-responsive">
<div align="right">
<button type="button" name="age" id="age" data-toggle="modal" data-target="#add_data_Modal" class="btn btn-warning">Add</button>
</div>
<br />
<div id="employee_table">
<table class="table table-bordered">
<tr>
<th width="70%">Employee Name</th>
<th width="30%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
<div id="add_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">PHP Ajax Insert Data in MySQL By Using Bootstrap Modal</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Enter Employee Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label>Enter Employee Address</label>
<textarea name="address" id="address" class="form-control"></textarea>
<br />
<label>Select Gender</label>
<select name="gender" id="gender" class="form-control">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<br />
<label>Enter Designation</label>
<input type="text" name="designation" id="designation" class="form-control" />
<br />
<label>Enter Age</label>
<input type="text" name="age" id="age" class="form-control" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#name').val() == "")
{
alert("Name is required");
}
else if($('#address').val() == '')
{
alert("Address is required");
}
else if($('#designation').val() == '')
{
alert("Designation is required");
}
else
{
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
});
$(document).on('click', '.view_data', function(){
//$('#dataModal').modal();
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"POST",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal('show');
}
});
});
});
</script>
insert.php
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(!empty($_POST))
{
$output = '';
$name = mysqli_real_escape_string($connect, $_POST["name"]);
$address = mysqli_real_escape_string($connect, $_POST["address"]);
$gender = mysqli_real_escape_string($connect, $_POST["gender"]);
$designation = mysqli_real_escape_string($connect, $_POST["designation"]);
$age = mysqli_real_escape_string($connect, $_POST["age"]);
$query = "
INSERT INTO employee(name, address, gender, designation, age)
VALUES('$name', '$address', '$gender', '$designation', '$age')
";
if(mysqli_query($connect, $query))
{
$output .= '<label class="text-success">Data Inserted</label>';
$select_query = "SELECT * FROM employee ORDER BY id DESC";
$result = mysqli_query($connect, $select_query);
$output .= '
<table class="table table-bordered">
<tr>
<th width="70%">Employee Name</th>
<th width="30%">View</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>' . $row["name"] . '</td>
<td><input type="button" name="view" value="view" id="' . $row["id"] . '" class="btn btn-info btn-xs view_data" /></td>
</tr>
';
}
$output .= '</table>';
}
echo $output;
}
?>
select.php
<?php
//select.php
if(isset($_POST["employee_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM employee WHERE id = '".$_POST["employee_id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td width="30%"><label>Name</label></td>
<td width="70%">'.$row["name"].'</td>
</tr>
<tr>
<td width="30%"><label>Address</label></td>
<td width="70%">'.$row["address"].'</td>
</tr>
<tr>
<td width="30%"><label>Gender</label></td>
<td width="70%">'.$row["gender"].'</td>
</tr>
<tr>
<td width="30%"><label>Designation</label></td>
<td width="70%">'.$row["designation"].'</td>
</tr>
<tr>
<td width="30%"><label>Age</label></td>
<td width="70%">'.$row["age"].'</td>
</tr>
';
}
$output .= '</table></div>';
echo $output;
}
?>
Database
--
-- Table structure for table `tbl_employee`
--
CREATE TABLE IF NOT EXISTS `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`address` text NOT NULL,
`gender` varchar(10) NOT NULL,
`designation` varchar(100) NOT NULL,
`age` int(11) NOT NULL,
`image` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=185 ;
--
-- Dumping data for table `tbl_employee`
--
INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `image`) VALUES
(1, 'Bruce Tom', '656 Edsel Road\r\nSherman Oaks, CA 91403', 'Male', 'Driver', 36, '1.jpg'),
(5, 'Clara Gilliam', '63 Woodridge Lane\r\nMemphis, TN 38138', 'Female', 'Programmer', 24, '2.jpg'),
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, '3.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 32, '4.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, '5.jpg'),
(175, 'Ronald D. Colella', '1571 Bingamon Branch Road, Barrington, IL 60010', 'Male', 'Top executive', 32, '6.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 38, '7.jpg'),
(161, 'Glenda J. Stewart', '3482 Pursglove Court, Rossburg, OH 45362', 'Female', 'Cost consultant', 28, '8.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 64, '9.jpg'),
(163, 'William C. Wright', '2653 Pyramid Valley Road, Cedar Rapids, IA 52404', 'Male', 'Political geographer', 33, '10.jpg'),
(178, 'Sara K. Ebert', '1197 Nelm Street\r\nMc Lean, VA 22102', 'Female', 'Billing machine operator', 50, ''),
(177, 'Patricia L. Scott', '1584 Dennison Street\r\nModesto, CA 95354', 'Female', 'Urban and regional planner', 54, ''),
(179, 'James K. Ridgway', '3462 Jody Road\r\nWayne, PA 19088', 'Female', 'Recreation leader', 41, ''),
(180, 'Stephen A. Crook', '448 Deercove Drive\r\nDallas, TX 75201', 'Male', 'Optical goods worker', 36, ''),
(181, 'Kimberly J. Ellis', '4905 Holt Street\r\nFort Lauderdale, FL 33301', 'Male', 'Dressing room attendant', 24, ''),
(182, 'Elizabeth N. Bradley', '1399 Randall Drive\r\nHonolulu, HI 96819', 'Female', ' Software quality assurance analyst', 25, ''),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, ''),
(184, 'Mark Stone', '021, Big street, NYC', 'Male', 'Head of IT', 41, '');
AWESOME AS ALWAYS
ReplyDeleteFantastic you guy may God bless you but can you make tutorial on privacy settings like facebook and Twitter does?? thks in advance
ReplyDeleteThanx alot this is really a great tips and techniques
ReplyDeletecan u give me the code for 'delete data'?? it would be great ..
ReplyDeleteAnd amazing job Weblesson!!
Hi, I've used downloaded the code from your site and set it in my local server. Everything is fine except the 'INSERTION' isn't working. When I try to add data, it says inserting and modal closes but it never inserts data into DB. Any idea what I'm doing wrong? There's no problem with DB connection just so you know.
ReplyDeleteJust change the name of database
Deletenot working
ReplyDeletewhy cancel your canal youtube , friends
ReplyDeleteAmigo porque cancelaron tu canal en youtube. You are so good thanks you , We need watch it, please
ReplyDeleteThanks for the great job.
ReplyDeleteWhere can I find a link to those scripts and the database
Nice works
ReplyDeleteThanks for your tutorial...
ReplyDeleteHow to if validation rule use php , not javascript and when empty text will show alert , alert like alert like botstrape...
Please help me...
I love your stuff. my number one fan this year....anyways, am trying to run this code for this tutorial and I have a rather unexpected error. Kindly help me out with this "
ReplyDeleteWarning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\scholars\modal_edit\index.php on line 32"
its in line 32 of your code
thanks
Thank you for your tutorial. It really helped me :)
ReplyDeletei dont know but there is an error in line 32 in index.php
ReplyDeleteLine 32 has an error at index.php
ReplyDeleteI can't get the image when i try to pass this. :(
ReplyDeletei click online demo and then when I press Add button the modal does not appearing
ReplyDeleteusman fakhar here to see th e
ReplyDeleteGreat ...
ReplyDeleteGood job
ReplyDeleteWarning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\tryouts\index.php on line 34
ReplyDeleteplease may anyone assist ,have the above error coming out
Amazing Job Weblesson
ReplyDeleteThank You
so easy you have to check the tables names use tbl_employee instead of employee thats it
ReplyDeleteThat's cool. Thanks for that tutorial, you have really saved a lot of my time.
ReplyDeleteWhat about a scenario when we have to use multiple modals to insert data into database...
ReplyDeleteWarning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\PHP-Ajax\index.php on line 33
ReplyDeletewhat does it means?
check your created table name and source code table name
ReplyDeleteHi! can you please help me? the view button in insert.php is not working on me, i think its not getting the data from the index.php, pls help me
ReplyDeletemake delete and edit pls
ReplyDeleteThank You so much
ReplyDeleteGap yo. Daxshat....:)
ReplyDelete