Bootstrap modal does not showing information - javascript

I have entered an internship for 6 month and I'm currently developing a web system using Bootstrap modal. I am experiencing an issue where my modal view is failing to show any information. There are no errors in the scripting but I do not know how to fix it. Its just blank. Any suggestion?
This is modal view for staff detail which is showing no information:
Below is the code from the two of files that are being used to show the modal view.
index.html
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_user ORDER BY user_id DESC";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>ADD NEW USER</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">Admin Log Site </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 New User</button>
</div>
<br />
<div id="employee_table">
<table class="table table-bordered">
<tr>
<th width="70%">Staff Name</th>
<th width="30%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["uname"]; ?></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["user_id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
<!-- modal insert division -->
<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">ADMIN SITE</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Enter Staff Username</label>
<input type="text" name="uname" id="uname" class="form-control" />
<br />
<label>Enter Staff ID</label>
<input type="text" name="staff_number" id="staff_number" class="form-control" />
<br />
<label>Staff Roles</label>
<select name="staff_role" id="staff_role" class="form-control">
<option value="Administration">Administration</option>
<option value="Project Manager">Project Manager</option>
<option value="Staff">Staff</option>
</select>
<br />
<label>Password</label>
<input type="text" name="password" id="password" class="form-control" />
<br />
<input type="submit" name="insert" id="insert" value="Add user" 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>
<!-- modal view employer -->
<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">Staff 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($('#uname').val() == "")
{
alert("Name is required");
}
else if($('#staff_number').val() == "")
{
alert("Staff id is required");
}
else if($('#staff_role').val() == "")
{
alert("Staff role is required");
}
else if($('#password').val() == "")
{
alert("password is required");
}
else
{
$.ajax({
url:"insertdata.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 user_id = $(this).attr("user_id");
$.ajax({
url:"view.php",
method:"POST",
data:{user_id:user_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal('show');
}
});
});
});
</script>
For the view inforamtion as follow.
view.php
<?php
//select.php
if(isset($_POST["user_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_user WHERE user_id = '".$_POST["user_id"]."'";
//$query = "SELECT * FROM tbl_user WHERE user_id = '".$_POST["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> Staff Name</label></td>
<td width="70%">'.$row["uname"].'</td>
</tr>
<tr>
<td width="30%"><label>Staff Id</label></td>
<td width="70%">'.$row["staff_number"].'</td>
</tr>
<tr>
<td width="30%"><label>Staff Role</label></td>
<td width="70%">'.$row["staff_role"].'</td>
</tr>
<tr>
<td width="30%"><label>password</label></td>
<td width="70%">'.$row["password"].'</td>
</tr>
';
}
$output .= '</table></div>';
echo $output;
}
?>

Your problem is that your $.ajax POST is sending JSON data but your PHP view is looking for items in $_POST.
To set $_POST values try this:
$.ajax({
url: "view.php",
method: "POST",
data: "user_id="+user_id,
success: function(data) {
$('#employee_detail').html(data);
$('#dataModal').modal('show');
}
});
Note: Typically your input elements would be inside of a <form> tag. When they are you can use $('#formid').serialize() to convert your input elements into a string that you can pass to the ajax call as the data variable.
For example:
<form id="getUserDetails">
<label for="user_id">A bar</label>
<input id="user_id" name="user_id" type="text" value="" />
<input type="submit" value="Send" onclick="PostThis();return false;
/>
</form>
var data = $('#getUserDetails').serialize();
$.ajax({
url: "test.php",
type: "post",
data: data ,
success: function (response) {
$('#employee_detail').html(response);
$('#dataModal').modal('show');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Related

Dynamic Loading of Data Via Ajax

I am new to AJAX and I am trying to load some data when clicked on a button to a modal, But the expected result is not being rendered and there are no errors thrown in the Developers Console.
The code AJAX code is as follows,
<script>
$(document).ready(function()
{
$(document).on('click','.edit_data', function(){
var employee_id = $(this).attr("User_ID");
$.ajax({
url:"fetchuser.php",
method:"POST",
data:{employee_id:employee_id},
dataType:"json",
success:function(data){
$('#floatingInputname').val(data.floatingInputname);
$('#add_data_Modal').modal('show');
}
});
});
});
</script>
And the fetchuser.php code is as follows,
<?php
include 'config.php';
if (isset($_POST['employee_id'])) {
$query = "SELECT * FROM gusers WHERE User_ID = '".$_POST['employee_id']."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
The HTML table structure where I have a button to be clicked for the modal with the data to load is as follows,
<table class="table" id="myTable" style="width: 100%;">
<thead>
<th scope="col">Image</th>
<th scope="col">Name</th>
<th scope="col">NIC</th>
<th scope="col">Contact</th>
<th scope="col">Role</th>
<th scope="col"></th>
</thead>
<tbody>
<?php
$queryguser = "SELECT * FROM `gusers`";
$gusersresult = mysqli_query($conn,$queryguser);
if ($gusersresult->num_rows>0) {
while ($gusersrow = mysqli_fetch_assoc($gusersresult)) {
?>
<tr>
<td scope="row">
<?php
if (empty($gusersrow['Image'])|| $gusersrow['Image']==null) {
?>
<img src="img/question (1).png" alt="No Profile" style="width:75px; height:75px; border-
radius:20px;">
<?php
}
else{
echo '<img src="data:image;base64,'.base64_encode($gusersrow['Image']).'" alt="Profile Image"
style="width:75px; height:75px; border-radius:50%;">';
}
?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['User_Name']; ?>"
onBlur="inlineedit(this,'User_Name','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["User_Name"]; ?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['User_NIC']; ?>"
onBlur="inlineedit(this,'User_NIC','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["User_NIC"]; ?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['User_Contact']; ?>"
onBlur="inlineedit(this,'User_Contact','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["User_Contact"]; ?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['Role']; ?>"
onBlur="inlineedit(this,'Role','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["Role"]; ?>
</td>
<td scope="row" class="text-center"><input type="button" name="edit" value="Edit" id="<?php echo
$gusersrow["User_ID"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
</tr>
<?php
}
}else{
echo "No Records Found";
}
?>
</tbody>
</table>
And the Modal i want the data to be displayed
<div class="modal fade" id="exampleModaluserupdate" tabindex="-1" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update User Data</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="row" style="width:100%;">
<div class="col-md-6">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputname">
<label for="floatingInputname">Name</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputnic">
<label for="floatingInputnic">NIC</label>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Further to this i have the following JS scripts loaded in my <head> tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart

Having difficulty identifying what is throwing the error. Have removed all white space. Using CodeAnywhere as my IDE as it is a requirement for me. Any help would be appreciated.
Full error:
Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart.php:134) in /home/cabox/workspace/Project/ShoppingCart.php on line 169
Code:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "lab"); //connect to the db
if(isset($_POST["add_to_cart"])) //if the add to cart value is set
{
if(isset($_SESSION["shopping_cart"])) //if the shopping cart session is set
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
//if there are values in your shopping cart loop through and display them
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("Item Already Added")</script>';
//restriction on design - can only add one instance of each product, delete if you want to add more
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
//when you select 'Remove', delete the values based on id. Alert box will show on completition
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item has been removed from Shopping Cart")</script>';
echo '<script>window.location="ShoppingCart.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<!-- AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.-->
<link rel="stylesheet" type="text/css" href="thePerfectPair.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</head>
<body>
<nav class="navigationBar">
<!--Establishing the top left hand side of the Navigation Bar-->
<div class="leftTopNavBar">
€ EUR |
<!--The following produces a pop up sign up form that is validated through javascript functions in the following code.
I implemented this pop up form to create a different design element as opposed to just referring users to another page.
All design element are assigned in the css file and it involved calling many different classes in order not to conflict
with other forms and input boxes contained in the website-->
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;" class="SignUpBtn0">SIGN UP |</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content" action="/action_page.php">
<div class="container1">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account with Perfect Pair!</p>
<hr>
<b>Email</b>
<input type="text" placeholder="Enter Email" name="email" required>
<b>Password</b>
<input type="password" placeholder="Enter Password" name="psw" required>
<b>Repeat Password</b>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
SAVED ITEMS
</div>
<!--Establishing the right side of the navBar-->
<div class="rightTopNavBar">
<input type="search" placeholder="Search..." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
LOGIN | CART
<i class="fa fa-shopping-cart" style="font-size:20px"></i>
</div>
<!--Establishing the middle of the navBar-->
<div class="middleTopNavBar">
<img src="Images/perfectPairLogo.png" class="logoHeader" alt="logo" width="100" height="100">
</div>
<!--Establishing bottom navBar-->
<div class="bottomNavBar">
<i class="fa fa-home" style="font-size:36px"> </i>
 HEELS 
 SANDALS 
 BOOTS 
 TRAINERS 
 FLATS 
 SHOPPING CART </div></nav>
<div class="container">
<br><?php $query="SELECT*FROM tbl_product1 ORDER BY id ASC"; $result=mysqli_query($connect, $query); if(mysqli_num_rows($result)>0){while($row=mysqli_fetch_array($result)){?><div class="col-md-4">
<form method="post" class="phpForm" action="ShoppingCart.php?action=add&id=<?php echo $row["id"];?>" >
<div class="formStyleDiv" style=" background-color:#f1f1f1; border-radius:1px; padding:16px; width:25%;" align="center">
<img src="Images/<?php echo $row["image"];?>" class="img-responsive" style="height: 200px;" />
<h4 class="text-info"><?php echo $row["name"];?></h4><br />
<h4 class="text-danger">€<?php echo $row["price"];?></h4>
<input type="text" name="quantity" value="1" class="form-control" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"];?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"];?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="submitBtn" class="btn btn-success" value="Add to Cart" /></div>
</form>
</div><?php
}
}
?><div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive" >
<table>
<tr>
<th width="40%" align="left">Item Name</th>
<th width="10%" align="left">Quantity</th>
<th width="20%" align="left">Price</th>
<th width="15%" align="left">Total</th>
<th width="5%" align="left">Action</th>
</tr><?php if(!empty($_SESSION["shopping_cart"])) { $total = 0; foreach($_SESSION["shopping_cart"] as $keys => $values){?><tr>
<td><?php echo $values["item_name"];?></td>
<td><?php echo $values["item_quantity"];?></td>
<td>€<?php echo $values["item_price"];?></td>
<td>€<?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
<td><span class="text-danger">Remove</span></td>
</tr><?php $total = $total + ($values["item_quantity"] * $values["item_price"]);}?><tr>
<td colspan="3" align="right">Total</td>
<td align="right">€<?php echo number_format($total, 2); ?></td>
<td></td>
</tr><?php $cookie_name="Total"; setcookie($cookie_name, $total, time()+(86400*30),"/");}?></table></div>
<input type="button" class="submitFormBtn" name="submit" value= "Submit" onclick="window.open ('success.php','_self',false)" /><br />
</div>
</div>
<br />
</body>
</html>

How to multiple update rows with modal bottstrap

hello guys can you help me with my problem, i want to update multiple rows with modal bootstrap
So when I check the line and press the update button, it will appear modal bootstrap and I will update from there
I'm having trouble finding the script, can you help me finish my code?
this is the explanation
I checked the line
After that I press "Pindah Department" or in english "Move Departemen"
this basically updates quickly, just you check the line and press the "Move Departement" button, then bootstrap capital appears and you will select the value in the dropdown to update the line
this is my view :
<div class="row">
<div class="col-md-12">
<div class="panel panel-info">
<div class="panel-heading">Data Siswa Departemen ......</div>
<div class="panel-body">
<table id="emp_id" class="table table-bordered dt-responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</thead>
<tbody>
<?php
foreach($data as $d){
?>
<tr>
<td>
<input class="childbox" width="1%" type="checkbox" name="msg[]" align="center" value="" data-userid="<?php echo $d['emp_id'] ?>"/>
</td>
<td width="1%" align="center"><?php echo $d['emp_id']; ?></td>
<td class="data-check"><?php echo $d['first_name']; ?></td>
<td class="data-check"><?php echo $d['nik']; ?></td>
<td class="data-check"><?php echo $d['gender']=='0' ? 'Laki-Laki' : 'Perempuan'; ?></td>
<td class="data-check"><?php echo $d['pin']; ?></td>
<td class="data-check"><?php echo $d['dept_name']; ?></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</tfoot>
</table>
</div>
<div class="panel-footer">
<button class="btn btn-success" onclick="edit_book(<?php echo $d['emp_id'];?>)"> Move Departemen</button>
</div>
</div><!--end panel-->
<script src="<?php echo base_url() ?>assets/baru/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url() ?>assets/baru/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url() ?>assets/baru/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
$('#emp_id').DataTable( {
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
} );
$("input[name='checkAll']").click(function() {
var checked = $(this).attr("checked");
$("#emp_id tr td input:checkbox").attr("checked", checked); });
} );
function toggle(id) {
checkboxes = document.getElementsByName('msg[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = id.checked;
}
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: prepareData(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
</script>
<!--modal-->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Update Departemen</h4>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="emp_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Departemen</label>
<div class="col-md-9">
<select name="dept_id_auto" class="form-control pull-right">
<?php
foreach($groups as $c)
{
echo '<option value="'.$c['dept_id_auto'].'">'.$c['dept_name'].'</option>';
}
?>
</select>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div><!-- end cols-->
</div><!--end row-->
I have trouble finding the script that will be called in the "Move Departement" button
This is my controller :
public function pindah_departemen()
{
// MASUKKAN PARAMETER DATA DISINI, BIASANYA HASIL DARI QUERY
$data = array(
'title' => 'Pindah Departemen',
'data' => $this->Pindah_dept_model->GetSiswa($this->input->get('filter_departemen'))
);
$data['groups'] = $this->Pindah_dept_model->getAllGroups();
$this->template->load('template','proses/pindah_departemen', $data);
}
public function book_update()
{
$data = array(
'dept_id_auto' => $this->input->post('dept_id_auto'),
);
$this->Pindah_dept_model->update_departemen(array('emp_id' => $this->input->post('emp_id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->Pindah_dept_model->get_by_id($id);
echo json_encode($data);
}
This is my Model :
class Pindah_dept_model extends CI_Model
{
var $table = 'emp';
public function GetSiswa($dep=NULL)
{
$this->db->select(array('emp_id', 'first_name', 'nik', 'gender', 'pin', 'dept_name'))
->from('emp AS e')
->join('dept AS d','d.dept_id_auto = e.dept_id_auto', 'left');
if(!empty($dep)) $this->db->where('d.dept_id_auto', $dep);
$data = $this->db->order_by('emp_id','ASC')->get();
return $data->result_array();
}
public function getAllGroups()
{
$query = $this->db->query('SELECT dept_id_auto,dept_name FROM dept');
return $query->result_array();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('emp_id',$id);
$query = $this->db->get();
return $query->row();
}
public function update_departemen($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
please guys help me finish my code, i'm looking for a way out for my code for 2 weeks and still no results
Thanks Before
I don't know if I'm late or not.
You can try do something like below.
HTML
<label>Value 1 <input name='checkme[]' type='checkbox' value='1'></label><br>
<label>Value 2 <input name='checkme[]' type='checkbox' value='2'></label><br>
<label>Value 3 <input name='checkme[]' type='checkbox' value='3'></label><br>
<label>Value 4 <input name='checkme[]' type='checkbox' value='4'></label><br>
<br>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_form" >Open Sesame</button>
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Update Departemen</h4>
</div>
<form action="#" id="form" class="form-horizontal">
<div class="modal-body form">
<input type="hidden" value="" name="emp_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Departemen</label>
<div class="col-md-9">
<select name="dept_id_auto" class="form-control pull-right">
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">* This is supposed to be hidden value</label>
<div class="col-md-9">
<input name='list_check'>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btnSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
Add hidden input, and we will get the checked value and store here later.
JAVASCRIPT
$(document).ready(function(){
$('#modal_form').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var vals = $('input:checkbox[name="checkme[]"]').map(function() {
return this.checked ? this.value : undefined;
}).get();
var modal = $(this);
modal.find('.modal-title').text("Open Sesame : Most code in here from bootstrap documentation. XD"); // just for fun.
modal.find(".modal-body input[name='list_check']").val(vals);
});
$("form").on("submit",function(x){
var val_submit = $(this).serialize(); // data to be send via ajax
alert("POST DATA : "+val_submit+"\n This is the value you will submit. The rest you can figure it out. Use explode() to split the list_check. And update like you want it.");
x.preventDefault();
});
});
After the button to open the modal. We will get the value from checkbox name checkme[]. This data need to be explode later in your php.
And try submit it.
I'm not going to take all your code. you need to figure out the rest by yourself. I just prepare example code that can be use. Maybe just like you want it. :)
JSFiddle Example : https://jsfiddle.net/synz/pyb7rjdo/

php bootstrap error with modal

I have the below scripts running but once I add a remote file link for the modal, it will not update.
I want to edit from a modal
within that modal window, confirm the data was submitted successfully
on close, refresh the crud.
Any help will be appreciated.
I'm modifying the class.crud.php file to include this line
removing
<i class="glyphicon glyphicon-edit"></i>
replacing with
<a data-toggle="modal" class="btn btn-info" href="edit-data.php?edit_id=<?php print($row['id']); ?>" data-target="#myModal"><i class="glyphicon glyphicon-edit"></i></a>
INDEX.PHP
<?php include_once 'dbconfig.php'; ?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<table class='table table-bordered table-responsive'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Contact No</th>
<th colspan="2" align="center">Actions</th>
</tr>
<?php
$query = "SELECT * FROM tblUsers";
$records_per_page=10;
$newquery = $crud->paging($query,$records_per_page);
$crud->dataview($newquery);
?>
<tr>
<td colspan="7" align="center">
<div class="pagination-wrap">
<?php $crud->paginglink($query,$records_per_page); ?>
</div>
</td>
</tr>
</table>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div> <!-- /.modal-content -->
</div> <!-- /.modal-dialog -->
</div> <!-- /.modal -->
<?php include_once 'footer.php'; ?>
CLASS.CRUD.PHP
public function update($id,$fname,$lname,$email,$level_id)
{
try
{
$stmt=$this->db->prepare("UPDATE tblUsers SET firstname=:fname,
lastname=:lname,
email=:email,
level_id=:contact
WHERE id=:id ");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":contact",$level_id);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM tblUsers WHERE id=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
/* paging */
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['firstname']); ?></td>
<td><?php print($row['lastname']); ?></td>
<td><?php print($row['email']); ?></td>
<td><?php print($row['level_id']); ?></td>
<td align="center">
<i class="glyphicon glyphicon-edit"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
EDIT-DATA.PHP
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
$id = $_GET['edit_id'];
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$email = $_POST['email'];
$level_id = $_POST['level_id'];
if($crud->update($id,$fname,$lname,$email,$level_id))
{
$msg = "<div class='alert alert-info'>
<strong>WOW!</strong> Record was updated successfully <a href='index.php'>HOME</a>!
</div>";
}
else
{
$msg = "<div class='alert alert-warning'>
<strong>SORRY!</strong> ERROR while updating record !
</div>";
}
}
if(isset($_GET['edit_id']))
{
$id = $_GET['edit_id'];
extract($crud->getID($id));
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($msg))
{
echo $msg;
}
?>
</div>
<div class="clearfix"></div>
<br />
<div class="modal-header" id="myModal">
<form method='post'>
<div class="form-group">
<label for="email">First Name:</label>
<input type='text' name='firstname' class='form-control' value="<?php echo $firstname; ?>" required>
</div>
<div class="form-group">
<label for="email">Last Name:</label>
<input type='text' name='lastname' class='form-control' value="<?php echo $lastname; ?>" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control' value="<?php echo $email; ?>" required>
</div>
<div class="form-group">
<label for="email">Level ID:</label>
<input type='text' name='level_id' class='form-control' value="<?php echo $level_id; ?>" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="btn-update">Save changes</button>
</div>
</form>
</div>
Try this method.
Load a bootstrap modal through ajax
Wrap your a tag inside div for easy visibility.
<div id="edit_btn">
<a data-toggle="modal" id="modal-<?php print($row['id']);?> " class="btn btn-info" href="#"><i class="glyphicon glyphicon-edit"></i></a>
</div>
index.php
<?php include_once 'dbconfig.php'; ?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<table class='table table-bordered table-responsive'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Contact No</th>
<th colspan="2" align="center">Actions</th>
</tr>
<?php
$query = "SELECT * FROM tblUsers";
$records_per_page=10;
$newquery = $crud->paging($query,$records_per_page);
$crud->dataview($newquery);
?>
<tr>
<td colspan="7" align="center">
<div class="pagination-wrap">
<?php $crud->paginglink($query,$records_per_page); ?>
</div>
</td>
</tr>
</table>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$("#edit_btn a").click(function() {
var Id = jQuery(this).attr("id");
$.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : "edit-data.php?edit_id=<?php print($row['id']); ?>",
success: function(response) {
if(response) {
$('body').append(response);
$('#modal_'+Id).modal('show');
$(document).on('hidden.bs.modal', modal_id, function (event) {
$(this).remove();
});
} else {
alert('Error');
}
}
});
});
});
</script>
Shift modal and insert it inside EDIT-DATA.PHP
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
$id = $_GET['edit_id'];
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$email = $_POST['email'];
$level_id = $_POST['level_id'];
if($crud->update($id,$fname,$lname,$email,$level_id))
{
$msg = "<div class='alert alert-info'>
<strong>WOW!</strong> Record was updated successfully <a href='index.php'>HOME</a>!
</div>";
}
else
{
$msg = "<div class='alert alert-warning'>
<strong>SORRY!</strong> ERROR while updating record !
</div>";
}
}
if(isset($_GET['edit_id']))
{
$id = $_GET['edit_id'];
extract($crud->getID($id));
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($msg))
{
echo $msg;
}
?>
</div>
<div class="clearfix"></div>
<br />
<div class="modal-header" id="myModal">
<form method='post'>
<div class="form-group">
<label for="email">First Name:</label>
<input type='text' name='firstname' class='form-control' value="<?php echo $firstname; ?>" required>
</div>
<div class="form-group">
<label for="email">Last Name:</label>
<input type='text' name='lastname' class='form-control' value="<?php echo $lastname; ?>" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control' value="<?php echo $email; ?>" required>
</div>
<div class="form-group">
<label for="email">Level ID:</label>
<input type='text' name='level_id' class='form-control' value="<?php echo $level_id; ?>" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="btn-update">Save changes</button>
</div>
</form>
</div>
</div> <!-- /.modal-content -->
</div> <!-- /.modal-dialog -->
</div> <!-- /.modal -->
index.php
<!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=utf-8" />
<title>Bootstrap</title>
<link href="bootstrap.min.css" rel="stylesheet" media="screen">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
<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>
</head>
<body>
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<h1>nav bar</h1>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="container">
<table class='table table-bordered table-responsive'>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>E - mail ID</th>
<th>Contact No</th>
<th colspan="2" align="center">Actions</th>
</tr>
<tr>
<td>1</td>
<td>James</td>
<td>Smith</td>
<td>james#gmail.com</td>
<td>1</td>
<td align="center">
<div id="edit_btn">
<a data-toggle="modal" id="modal-1 " class="btn btn-info" href="edit-data.php?edit_id=1">test</i></a>
</div>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<tr>
<td>2</td>
<td></td>
<td></td>
<td>admin#gmail.com</td>
<td>2</td>
<td align="center">
<div id="edit_btn">
<a data-toggle="modal" id="modal-2 " class="btn btn-info" href="edit-data.php?edit_id=2">test</i></a>
</div>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<tr>
<td>3</td>
<td></td>
<td></td>
<td>james.Smith#gmail.com</td>
<td>3</td>
<td align="center">
<div id="edit_btn">
<a data-toggle="modal" id="modal-3 " class="btn btn-info" href="edit-data.php?edit_id=3">test</i></a>
</div>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<tr>
<td colspan="7" align="center">
<div class="pagination-wrap">
<ul class="pagination">
<li><a href='/test/index.php?page_no=1' style='color:red;'>1</a></li>
</ul>
</div>
</td>
</tr>
</table>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<script type='text/javascript'>
$(document).ready(function() {
$("#edit_btn a").on('click',function() {
var Id = jQuery(this).attr("id");
$.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : "edit-data.php?edit_id=",
success: function(response) {
if(response) {
$('body').append(response);
$('#modal_'+Id).modal('show');
$(document).on('hidden.bs.modal', modal_id, function (event) {
$(this).remove();
});
} else {
alert('Error');
}
}
});
});
});
</script>
<div class="container">
<div class="alert alert-info">
</div>
</div>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
edit-date.php
<!-- Modal -->
<!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=utf-8" />
<title>PDO OOP CRUD using Bootstrap</title>
<link href="bootstrap.min.css" rel="stylesheet" media="screen">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
<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>
</head>
<body>
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<h1>nav bar</h1>
</div>
</div>
</div>
<div class="modal-header" id="myModal">
<div class="modal-body">
<form method='post'>
<div class="form-group">
<label for="email">First Name:</label>
<input type='text' name='firstname' class='form-control' value="Phil" required>
</div>
<div class="form-group">
<label for="email">Last Name:</label>
<input type='text' name='lastname' class='form-control' value="Smith" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control' value="phil#gmail.com" required>
</div>
<div class="form-group">
<label for="email">Level ID:</label>
<input type='text' name='level_id' class='form-control' value="6" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="btn-update">Save changes</button>
</div>
</form>
</div>
</div>

Creating a CRUD using PHP + Bootstrap Modal + Mysql + JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a page with a button to insert a new user, with fields "country","name" and "company". Then, in the same page, I need to list those datas and in front each item it'll appear two buttons, "edit" and "delete". At edit button, I need to display a Modal window (bootstrap), so I could update this data.
I hope someone could help me.
Thanks
Sorry, I've forgot to paste the code.
This is my index.php:
<form action="inserir.php" method="post" name="visitas" id="visitas">
<table class="table_geral" align="center" width="350" border="0" cellspacing="0" cellpadding="3">
<tr>
<td width="200">Pais:</td>
<td>
<?
$array_pais = array('Selecione...','Alemanha','Angola','Argentina','Bolívia','Brasil','Camarões','Canadá','Chile','China','Colombia',
'Costa Rica','Cuba','Dinamarca','Equador','Espanha','Estados Unidos','França','Holanda','Inglaterra','Itália','Japão',
'México','Nigéria','Panamá','Paraguai','Peru','Porto Rico','Portugal','Rússia','Senegal','Taiwan','Uruguai','Venezuela'
);
echo '<select class="form-control" style="width:330px" name="pais" id="pais">';
foreach($array_pais as $valor){
echo '<option>'.$valor.'</option>';
}
echo '</select>';
?>
</td>
<td height="29" valign="center" align="center" rowspan="3">&nbsp </td>
<td height="29" valign="center" align="center" rowspan="3">
<input type="submit" name="Submit" class="btn btn-success btn-lg" value=" + ">
</td>
</tr>
<tr>
<td width="411">Nome:</td>
<td width="339">
<input class="form-control" name="nome" type="text" id="nome" size="50">
</td>
</tr>
<tr>
<td width="411">Empresa:</td>
<td width="339">
<input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
</td>
</tr>
</table>
</form>
$sql = "SELECT * FROM tb_visitas ORDER BY empresa";
$limite = mysql_query("$sql"); ?>
<table data-toggle="table" data-cache="false">
<thead align="center">
<tr height="35px" valign="center" bgcolor="#B0E2FF" >
<th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
<th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
<th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
<th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
</tr>
</thead>
<? while($result = mysql_fetch_array($limite)){ ?>
<tbody>
<tr>
<td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
<td style="vertical-align:middle;"> <?=$result['pais']?></td>
<td style="vertical-align:middle;"> <?=$result['nome']?></td>
<td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
<td style="width:20px">
<form action="editar.php" method="post">
<a class="btn btn-primary glyphicon glyphicon-pencil" title="Editar" href="editar.php?id=<?=$result['id'];?>"></a>
</form>
</td>
<td style="width:20px">
<a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
</td>
</tr>
</tbody>
<?}?>
</table>
<div class="container">
<div class="modal fade" id="myModal" role="dialog">
<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">
<span class="glyphicon glyphicon-pencil"></span> Novo registro</h4>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
</div>
<script>
$('form').submit(function () {
var postdata = {
pais: $(this)[0].pais.value,
nome: $(this)[0].nome.value,
empresa: $(this)[0].empresa.value
}
$.post("inserir.php", postdata, function (d) {
$('#myModal').find(".modal-body").html(d);
$('#myModal').modal('show');
});
return false;
});
</script>
And it's my inserir.php:
<?
require("conexao.php");
$pais = $_POST['pais'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
if (($pais == "") || ($pais == "Selecione...") || ($nome == "") || ($empresa == "")) {
echo "Favor preencha todos os campos!";
} else {
$sql = mysql_query("SELECT nome FROM tb_visitas WHERE nome='$nome'");
if (mysql_num_rows($sql) > 0) {
echo "O nome <b>$nome</b> ja foi inserido na lista!";
} else {
$sqlinsert = "INSERT INTO tb_visitas VALUES (null, '$pais', '$nome', UPPER('$empresa'))";
mysql_query($sqlinsert) or die (mysql_error());
echo "Gravado com sucesso!";
}
}
?>
With assist from CodeGodie now I have this code, but I need to open a Modal window (bootstrap) to edit some register. However I don't know how to make it with AJAX. I feel sorry for my bad explanation and my English. Thanks
Sorry, but I'm beginner in php and ajax. There are much code that I've never seen :( ....Then, I'm having some difficulty to make it work out. I thought it was simplest. However I tried to make the files:
editar.php
$con = mysql_connect("localhost", "root", "", "visitas");
// Check connection
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];
$query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";
if (mysql_query($con, $query)) {
$res['response'] = true;
$res['message'] = "Record has been updated";
} else {
$res['response'] = false;
$res['message'] = "Error: " . $query . "<br>" . mysql_error($con);
}
echo json_encode($res);
deletar.php
<?php
require("conexao.php");
$id = $_POST['id'];
if (isset($_POST['id'])) {
$sql = "DELETE FROM tb_visitas WHERE id = $id";
$deletar = mysql_query($sql) or die (mysql_error());
}
?>
get_list.php
$con = mysql_connect("localhost", "root", "", "visitas");
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];
$query = "SELECT * FROM tb_visitas";
?>
conexão.php
<?
error_reporting(E_ALL ^ E_DEPRECATED);
$hostname = 'localhost';
$username = 'root';
$senha = '';
$banco = 'visitas';
$db = mysql_connect($hostname, $username, $senha);
mysql_set_charset('latin1',$db);
mysql_select_db($banco, $db) or die ("Não foi possível conectar ao banco MySQL");
?>
I see what you have now. Thanks for adding the code. I would first focus on design. It sounds like you want some sort of CRUD(Create Retrieve Update Delete) system. In that case, what I would do, is place the initial submission form on top (like what you have), and use modals to show any alert messages and the Edit form.
The design would look like this:
+-------------------------------------+
| Submit Form |
| - input |
| - input |
+-------------------------------------+
| List showing DB info |
| - result 1 (with Edit/Delete links) |
| - result 2 (with Edit/Delete links) |
| ... |
+-------------------------------------+
At page load, you will run an JS function, we can call it update_list(), that will use AJAX to fetch all the database info and parse it in the List container.
Then you will delegate Edit/Delete Click events to call the desired AJAX calls.
Keep in mind, this design structure separates everything in functions and uses AJAX to call on PHP scripts. The data will be sent via JSON.
Now, when you Submit the submission form, this will also use AJAX to send POST requests to PHP, then once submitted, JS will use Bootstrap's modal to show messages.
When the edit link is clicked, JS will again open a Bootstrap modal to show the edit form.
With that said, this is how I would do it :
<html>
<title>Modal</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/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>
<style>
#wrapper {
padding: 10px;
}
.modal-header, h4, .close {
background-color: #5cb85c;
color: white !important;
text-align: center;
font-size: 30px;
}
.modal-footer {
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div id="wrapper">
<form id="submit_form" role="form" style="width: 300px;">
<div class="form-group">
<label for="pais">Pais:</label>
<?php
$array_pais = array('Selecione...', 'Alemanha', 'Angola', 'Argentina', 'Bolívia', 'Brasil', 'Camarões', 'Canadá', 'Chile', 'China', 'Colombia',
'Costa Rica', 'Cuba', 'Dinamarca', 'Equador', 'Espanha', 'Estados Unidos', 'França', 'Holanda', 'Inglaterra', 'Itália', 'Japão',
'México', 'Nigéria', 'Panamá', 'Paraguai', 'Peru', 'Porto Rico', 'Portugal', 'Rússia', 'Senegal', 'Taiwan', 'Uruguai', 'Venezuela'
);
echo '<select class="form-control" name="pais" id="pais">';
foreach ($array_pais as $valor) {
echo '<option>' . $valor . '</option>';
}
echo '</select>';
?>
</div>
<div class="form-group">
<label for="nome">Nome:</label>
<input class="form-control" name="nome" type="text" id="nome" size="50">
</div>
<div class="form-group">
<label for="empresa">Empresa:</label>
<input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
</div>
<input type="submit" name="Submit" class="btn btn-success btn-lg" value="+">
</form>
<table id="list" class="table">
<thead align="center">
<tr bgcolor="#B0E2FF">
<th>PAÍS</th>
<th>NOME</th>
<th>EMPRESA</th>
<th>AÇÕES</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="modals_container">
<div class="modal fade" id="message_modal" role="dialog">
<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">Message</h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit_modal" role="dialog">
<div class="modal-dialog">
<form id="edit_form" class="form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit</h4>
</div>
<div class="modal-body">
<div class="form-group">
Country: <input id="country_input" type="text" name="country">
</div>
<div class="form-group">
Nome: <input id="username_input" type="text" name="username">
</div>
<div class="form-group">
Company: <input id="company_input" type="text" name="company">
</div>
<input id="id_input" type="hidden" name="id">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function update_list() {
$.getJSON("get_list.php", function (data) {
if (data.response) {
$("#list").find("tbody").empty();
data.results.forEach(function (i) {
console.log(i);
$("#list").find("tbody").append(
"<tr>" +
"<td>" + i.country + "</td>" +
"<td>" + i.username + "</td>" +
"<td>" + i.company + "</td>" +
"<td><a class='edit_link' href='" + JSON.stringify(i) + "'>edit</a> | <a class='delete_link' href='" + i.id + "'>delete</a></td>" +
"</tr>"
);
});
}
});
}
update_list();
$('#submit_form').submit(function () {
$.ajax({
url: "main.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#message_modal');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
$("#list").delegate('.edit_link', 'click', function (e) {
e.preventDefault();
var info = JSON.parse($(this).attr("href"));
var $modal = $("#edit_modal");
$modal.find("#country_input").val(info.country);
$modal.find("#company_input").val(info.company);
$modal.find("#username_input").val(info.username);
$modal.find("#id_input").val(info.id);
$modal.modal('show');
});
$('#edit_form').submit(function () {
$.ajax({
url: "edit.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#message_modal');
$("#edit_modal").modal('hide');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
</script>
</body>
</html>
edit.php should be something like this:
$con = mysqli_connect("localhost", "root", "", "test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$nome = $_POST['username'];
$company = $_POST['company'];
$country = $_POST['country'];
$query = "UPDATE table SET username = '$nome', company = '$company', country= '$country' WHERE id = $id ";
if (mysqli_query($con, $query)) {
$res['response'] = true;
$res['message'] = "Record has been updated";
} else {
$res['response'] = false;
$res['message'] = "Error: " . $query . "<br>" . mysqli_error($con);
}
echo json_encode($res);
Try this out, and let me know what you think.
I've not changed much php code of yours. I added little code to it.
In , i added code to call editar.php modal. In that script tag.. more code were there.. I don't know what is that.
index.php
//
Your original code here(No changes). From down, it started changing
//
<table data-toggle="table" data-cache="false">
<thead align="center">
<tr height="35px" valign="center" bgcolor="#B0E2FF" >
<th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
<th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
<th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
<th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
</tr>
</thead>
<? while($result = mysql_fetch_array($limite)){ ?>
<tbody>
<tr>
<td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
<td style="vertical-align:middle;"> <?=$result['pais']?></td>
<td style="vertical-align:middle;"> <?=$result['nome']?></td>
<td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
<td style="width:20px">
//Some Changes Here.. check it
<a class='btnEdit' href="#form_modal" data-toggle="modal" data-EditID="<?echo $result['id'];?>">
<span class='glyphicon glyphicon-pencil'></span>
<a>
</td>
<td style="width:20px">
<a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
</td>
</tr>
</tbody>
<?}?>
</table>
//Add this code.
<div id="form_modal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
//Added few codes in script for calling modal.
<script>
$('form').submit(function () {
var postdata = {
pais: $(this)[0].pais.value,
nome: $(this)[0].nome.value,
empresa: $(this)[0].empresa.value
}
$.post("inserir.php", postdata, function (d) {
$('#myModal').find(".modal-body").html(d);
$('#myModal').modal('show');
});
return false;
});
$('.btnEdit').click(function(){
var id=$(this).attr('data-EditID');
$.ajax({url:"editar.php?id="+id,cache:false,success:function(result){
$(".modal-content").html(result);
}});
});
</script>
Make One editar.php. Paste this below code in that page.
editar.php
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Novo registro
</h4>
</div>
<div class="modal-body" style='text-align:justify;'>
<?echo $_GET['id'];?>
//Show Details Here.
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>

Categories

Resources