Well, this is a crud application which contains add/edit/delete options and I wanted to implement in order to add an other button to view a selected row but my query doesn't work, I am sending an http request with Ajax and am getting the data but the query doesn't work.
Form_view.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1></h1>
<div class="col-sm-8">
<div class="well clearfix">
<div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
<span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
<table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
<th data-column-id="employee_name">Name</th>
<th data-column-id="employee_salary">Salary</th>
<th data-column-id="employee_age">Age</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div id="add_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_add">
<input type="hidden" value="add" name="action" id="action" >
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="name" name="name" required></input>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="salary" name="salary" required></input>
</div>
<div class="form-group">
<label for="salary" class="control-label">Age:</label>
<input type="text" class="form-control" id="age" name="age" required></input>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_add" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="edit_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_edit">
<input type="hidden" value="edit" name="action" id="action">
<input type="hidden" value="0" name="edit_id" id="edit_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="edit_name" name="edit_name">
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Age:</label>
<input type="text" class="form-control" id="edit_age" name="edit_age"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_edit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="view_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">View Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_view">
<input type="hidden" value="view" name="action" id="action">
<input type="hidden" value="0" name="view_id" id="view_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="view_name" name="view_name">
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="view_salary" name="view_salary"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Age:</label>
<input type="text" class="form-control" id="view_age" name="view_age"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_view" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var grid = $("#employee_grid").bootgrid({
ajax: true,
rowSelect: true,
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "response.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn-success btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn-danger btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button> " +
"<button type=\"button\" class=\"btn-warning btn-default command-view\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-eye-open\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#edit_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
$('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());
$('#edit_age').val(ele.siblings(':nth-of-type(4)').html());
} else {
alert('Now row selected! First select row, then click edit button');
}
}).end()
//View data
grid.find(".command-view").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#view_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#view_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#view_name').val(ele.siblings(':nth-of-type(2)').html());
$('#view_salary').val(ele.siblings(':nth-of-type(3)').html());
$('#view_age').val(ele.siblings(':nth-of-type(4)').html());
} else {
alert('error');
}
}).end()
//end view data
grid.find(".command-delete").on("click", function(e)
{
var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
alert(conf);
if(conf){
$.post('response.php', { id: $(this).data("row-id"), action:'delete'}
, function(){
// when ajax returns (callback),
$("#employee_grid").bootgrid('reload');
});
//$(this).parent('tr').remove();
//$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
}
});
});
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
}
});
}
$( "#command-add" ).click(function() {
$('#add_model').modal('show');
});
$( "#btn_add" ).click(function() {
ajaxAction('add');
});
$( "#btn_edit" ).click(function() {
ajaxAction('edit');
});
$( "#btn_view" ).click(function() {
ajaxAction('view');
});
});
</script>
response.php
<?php
//include connection file
include_once("connection.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Employee($connString);
switch($action) {
case 'add':
$empCls->insertEmployee($params);
break;
case 'view':
$empCls->viewEmployee($params);
break;
case 'edit':
$empCls->updateEmployee($params);
break;
case 'delete':
$empCls->deleteEmployee($params);
break;
default:
$empCls->getEmployees($params);
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getEmployees($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertEmployee($params) {
$data = array();;
$sql = "INSERT INTO `employee` (employee_name, employee_salary, employee_age) VALUES('" . $params["name"] . "', '" . $params["salary"] . "','" . $params["age"] . "'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_age LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) ) {
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
function updateEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."', employee_age='" . $params["edit_age"] . "' WHERE id='".$_POST["edit_id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
}
function viewEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Select employee_name FROM employee WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to view employee data");
}
function deleteEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "delete from `employee` WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
}
?>
My query to view the data is :
function viewEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Select employee_name FROM employee WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to view employee data");
}
Any idea , what should I do to select data from database and print them in html form ?
You are using the wrong variable name from $_REQUEST, you are using ìd when you should use view_id as it is configured in the form hidden field.
Try
function viewEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Select employee_name FROM employee WHERE id='".$params["view_id"]."'";
$result = mysqli_query($this->conn, $sql) or die("error to view employee data");
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}
Related
I have problem with my ajax,
here my index:
<form name="add_name" id="add_name">
<div class="col-lg-12">
<div class="form-row mb-2">
ID Kurir :
<div class="col">
<input type="text" id="idkurir" name="idkurir" placeholder="Input ID Kurir" class="idkurir" autofocus />
</div>
Nama Kurir :
<div class="col">
<input type="text" id="namakurir" name="namakurir" value="Nama Kurir" class="namakurir" readonly />
</div>
No Laporan :
<div class="col">
<input type="text" id="nolaporan" name="nolaporan" value="No Laporan" readonly />
</div>
Date :
<div class="col">
<?php $now=date('d-m-Y H:i'); ?>
<input type="text" name="date" value=<?php echo "'$now'"; ?> readonly />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<table class="table table-bordered" id="dynamic_field1">
<tr>
<td colspan=2 align=center><strong>Antar Ulang</strong></td>
</tr>
<tr>
<td><input type="text" name="awbau[]" placeholder="Enter AWB" class="form-control name_listau" /></td>
<td><button type="button" name="addau" id="addau" class="btn btn-success">Add More</button></td>
</tr>
</table>
</div>
<div class="col-lg-6">
<table class="table table-bordered" id="dynamic_field2">
<tr>
<td colspan=2 align=center><strong>Undelivery</strong></td>
</tr>
<tr>
<td><input type="text" name="awbundel[]" placeholder="Enter AWB" class="form-control name_listundel" /></td>
<td><button type="button" name="addundel" id="addundel" class="btn btn-success">Add More</button></td>
</tr>
</table>
</div>
</div>
<center><input type="button" name="submit" id="submit" class="btn btn-info btn-block mb-4 mr-2" value="Submit Data" /></center>
</form>
here my ajax script :
$(document).on("keypress", ".idkurir", function(e) {
var idkurir = $('#idkurir').val();
if (e.which == 13) {
$.ajax({
type: "POST",
url: "checkdata.php",
data: {
idkurir: idkurir
},
success: function(response) {
if (response == 1) {
alert("Kurir sudah laporan");
} else {
if (response == "ID Kurir tidak di temukan") {
alert(response);
} else {
var d = new Date();
var today_date = ("0" + d.getDate()).slice(-2) + ("0" + (d.getMonth() + 1)).slice(-2);
$('#nolaporan').val(idkurir + today_date);
$('#namakurir').val(response);
}
}
}
});
}
});
and here my checkdata to check if data exist :
session_start();
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("reportchecker", $connect);
$idkurir = $_POST["idkurir"];
$nolaporan = $idkurir . date("dm");
$sql = "SELECT * FROM jampulang WHERE nolaporan = '$nolaporan'";
$result = mysql_query($sql, $connect);
$count = mysql_num_rows($result);
$response = [];
$sql2 = "SELECT * FROM kurir WHERE idkurir = '$idkurir'";
$result2 = mysql_query($sql2, $connect) or die(mysql_error());
$count2 = mysql_num_rows($result2);
if ($count == 1) {
echo "1";
} else if ($count2 == 1) {
$row = mysql_fetch_array($result2) or die(mysql_error());
echo $row['nama'];
} else {
echo "ID Kurir tidak di temukan";
}
my problem is when response from checkdata = "ID Kurir tidak di temukan", ajax not showing alert and stop update field nolaporan and nama kurir
$('#nolaporan').val(idkurir + today_date);
$('#namakurir').val(response);
in my script above when reponse "ID Kurir tidak di temukan" still update field nolaporan and namakurir.
You can fix it on the client side using $.trim() like below:
if($.trim(response) == 'ID Kurir tidak di temukan') {
//do your code
}
I want to update my database using php ajax modal. When updating the relevant field { $('#main_id').val(data.id); } don't pass an id to the update query therefor an insertion occurs without executing the updating query.
console log details when trying to update
I tried to solve this but I couldn't. without updating the existing data it inserts a new record
here is my index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
$query = "SELECT * FROM tbl_main_category ORDER BY cat_Id DESC";
$result = mysqli_query($connect, $query);
?>
<div id="employee_table">
<table class="table table-bordered">
<tr> <th width="70%">Employee id</th>
<th width="70%">Employee Name</th>
<th width="15%">Edit</th>
<th width="15%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr> <td><?php echo $row["cat_Id"]; ?></td>
<td><?php echo $row["category_name"]; ?></td>
<td><input type="button" name="edit" value="Edit" id="<?php echo $row["cat_Id"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["cat_Id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
<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>
<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 Update MySQL Data Through Bootstrap Modal</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Enter Employee Name</label>
<input type="text" name="category_name" id="category_name" class="form-control" />
<br />
<input type="hidden" name="main_id" id="main_id" />
<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>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#insert').val("Insert");
$('#insert_form')[0].reset();
});
$(document).on('click', '.edit_data', function(){
console.log('test')
var main_id = $(this).attr("id");
console.log(main_id)
$.ajax({
url:"fetch.php",
method:"POST",
data:{main_id:main_id},
dataType:"json",
success:function(data){
console.log(data)
$('#category_name').val(data.category_name);
console.log(data.category_name)
$('#main_id').val(data.id);
console.log(data.id)
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
if(!empty($_POST))
{
$output = '';
$message = '';
$category_name = mysqli_real_escape_string($connect, $_POST["category_name"]);
if($_POST["main_id"] != '')
{
$query = "
UPDATE tbl_main_category
SET category_name='$category_name' WHERE cat_Id='".$_POST["main_id"]."'";
$message = 'Data Updated';
}
else
{
$query = "
INSERT INTO tbl_main_category(category_name)
VALUES('$category_name');
";
$message = 'Data Inserted';
}
fetch.php
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
if(isset($_POST["main_id"]))
{
$query = "SELECT * FROM tbl_main_category WHERE cat_Id = '".$_POST["main_id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
You have Fetched the value from $('#main_id').val(data.id) instead of $('#main_id').val(data.cat_Id);
You have fetched value of id instead of cat_Id
I have 2 forms, static and dynamic form. Dynamic is optional, depends on user if they want to submit more than one inputs. The insertion process works fine. Then, I have a function to check the availability for the input that user want to insert. The thing is, the live check availability only works in static form. How I want to call back the live check availability function inside the dynamic form? Your help is truly appreciate :)
index.php
//static form
<form action="" method="post" enctype="multipart/form-data">
<div class="field_wrapper">
<div class="row">
<div class="col-md-1">
<a rel="tooltip" title="Add" class="btn btn-info btn-icon add_button" href="javascript:void(0);"><i class="ti-plus"></i></a>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label pull-left">Category<star>*</star>
</label>
<input class="form-control" type="text" name="cat[]" id="cat" title="This field needed" required="true" placeholder="Student"/><span id="usercheck3" class="help-block pull-left"></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="btn btn-warning btn-fill btn-wd pull-right" name="submit2" id="submit2" type="submit" value="Add">
</div>
</div>
</div>
<br>
</form>
<script type="text/javascript">
$(document).ready(function(){
//live check availability
$('#cat').keyup(function() {
var usercheck3 = $(this).val();
$.post("check.php", {user_name3: usercheck3} , function(data)
{
if (data.status == true)
{
$('#usercheck3').parent('div').removeClass('has-error').addClass('has-success');
$('#submit2').attr("disabled", false);
} else {
$('#usercheck3').parent('div').removeClass('has-success').addClass('has-error');
$('#submit2').attr("disabled", true);
}
$('#usercheck3').html(data.msg);
},'json');
});
//dynamic form
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div class="form-group"><div class="row"><div class="col-md-1"><a rel="tooltip" title="Delete" class="btn btn-info btn-icon remove_button" href="javascript:void(0);"><i class="ti-minus"></i></a></div><div class="col-md-2"><label class="control-label pull-left">Category<star>*</star></label><input class="form-control" type="text" name="cat[]" id="cat" title="This field needed" required="true" placeholder="Student"/><span id="usercheck3" class="help-block pull-left"></span></div></div>';
var x = 1;
$(addButton).click(function(){
x++;
$(wrapper).append(fieldHTML);
});
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parents('.form-group').remove();
x--;
});
});
</script>
check.php
//db connection
if (isset($_POST['user_name3']) && $_POST['user_name3'] != '') {
$response = array();
$cat = $_POST['user_name3'];
$sql = "select cat from cat_tables where cat='" . $cat . "'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if ($count > 0) {
$response['status'] = false;
$response['msg'] = 'Not available';
} else {
$response['status'] = true;
$response['msg'] = 'Available';
}
}
echo json_encode($response);
I've fetched rows from MySQL and looped it with Bootstrap modal and I've made a form in modal from which the data is being sent to PHP script (update.php) with the help of ajax. But in return I am getting the output of last row only.
I need to get the record of specific student with its unique ID.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
while($row = mysqli_fetch_assoc($query_run)){
$id = $row['id'];
$name = $row['name'];
$rollno = $row['rollno'];
$contact = $row['contact'];
$address = $row['address'];
echo "<tr>";
echo '<td>' . $name . '</td>';
echo '<td>' . $rollno . '</td>';
echo '<td>' . $contact . '</td>';
echo '<td>' . $address . '</td>';
echo "<td><button class='btn btn-link btn-custom dis' data-toggle='modal' data-target='#myModal$id'>
EDIT</button> </td>";
echo '</tr>';
?>
<div class="modal fade" id="myModal<?php echo $id; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="rollno" value="<?php echo $rollno; ?>">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="contact" value="<?php echo $contact; ?>">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="address"><?php echo $address; ?></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php }
}?>
</tbody>
</table>
</body>
</html>
JS:
$(document).ready(function(){
var values, url;
$('#updateValues').submit(function(e){
e.preventDefault();
values = $(this).serialize();
url = $(this).attr('action');
$.post(url, values, function(data){
$('#results').html(data);
});
});
});
Update.php:
<?php
if(isset($_POST['name'])&&isset($_POST['rollno'])&&isset($_POST['contact'])&&isset($_POST['address'])){
$id = $_POST['id'];
$name = $_POST['name'];
$rollno = $_POST['rollno'];
$contact = $_POST['contact'];
$address = $_POST['address'];
echo "$id $name $rollno $contact $address";
}else{
echo 'ERROR!';
}
?>
This is not tested/debugged but refactor your code similar to this:
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
$out = '
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_assoc($query_run)){
$out .= '<tr class="trID_' .$row['id']. '">';
$out .= '<td class="td_name">' . $row['name'] . '</td>';
$out .= '<td class="td_rollno">' . $row['rollno'] . '</td>';
$out .= '<td class="td_contact">' . $row['contact'] . '</td>';
$out .= '<td class="td_address">' . $row['address'] . '</td>';
$out .= "<td><button class='td_btn btn btn-link btn-custom dis'>EDIT</button> </td>";
$out .= '</tr>';
}
$out .= '</tbody></table>
echo $out;
?>
<script>
$(document).ready(){
$('.td_btn').click(function(){
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var name = $row.find('.td_name').val();
var rollno = $row.find('.td_rollno').val();
var contact = $row.find('.td_contact').val();
var address = $row.find('.td_address').val();
$('#frm_id').val(rowID);
$('#frm_name').text(name);
$('#frm_rollno').text(rollno);
$('#frm_contact').text(contact);
$('#frm_address').text(address);
$('#myModal').modal('show');
});
});//END document.ready
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="frm_rollno">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php
}
}
?>
Notes:
(1) Create the entire table in a variable, then output the variable all at once.
(2) You only need one modal, not one modal for each table row. Therefore, remove modal creation from inside while loop.
(3) Use jQuery to:
(a) detect button click in row
(b) get table data for that row
(c) populate fields in modal
(d) display modal
You are using Bootstrap, which uses jQuery, so it makes sense to use jQuery to do this.
(4) Using jQuery to get values from table cells vs. input fields:
(a) .text() - from table cells
(b) .val() - from <input> or <textarea>
Here is a jsFiddle Demo you can play with that demonstrates how you can use jQuery to populate the modal depending on the row that was clicked.
I have this index.php code:
<form role="form" id="submit_form" class="form-horizontal">
<div class="panel-body">
<div class="form-group has-feedback">
<div class="col-sm-2">
<label class="control-label">País</label>
</div>
<div class="col-sm-9">
<?
$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>
<div class="form-group has-feedback">
<div class="col-sm-2">
<label class="control-label">Nome:</label>
</div>
<div class="col-sm-10">
<input id="nome" name="nome" class="form-control" type="text" placeholder="Digite o nome">
</div>
</div>
<div class="form-group has-feedback">
<div class="col-sm-2">
<label class="control-label">Empresa</label>
</div>
<div class="col-sm-10">
<input id="empresa" name="empresa" class="form-control" type="text" placeholder="Digite a empresa">
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col-sm-offset">
<div style="float:left; padding-right:30px">
<button type="submit" class="btn btn-lg btn-primary" aria-label="Left Align">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Adicionar
</button>
</div>
<div style="float:right;">
<button class="btn btn-lg btn-warning" onClick="parent.location='exibir.php'">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="jumbotron">
<table data-toggle="table" data-cache="false" class="table" id="list">
<thead align="center">
<tr bgcolor="#FFFFFF">
<th>PAÍS</th>
<th>NOME</th>
<th>EMPRESA</th>
<th>AÇÕES</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="inserir_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<span class="glyphicon glyphicon-file"></span> Inserir
</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="editar_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>
<h3 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Editar
</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label class="control-label">País:</label>
<input id="pais_input" name="nome" class="form-control" type="text" placeholder="Digite o pais">
</div>
<div class="form-group">
<label class="control-label">Nome:</label>
<input id="nome_input" name="nome" class="form-control" type="text" placeholder="Digite a empresa">
</div>
<div class="form-group">
<label class="control-label">Empresa:</label>
<input id="empresa_input" name="empresa" class="form-control" type="text" placeholder="Digite a empresa">
</div>
<input id="id_input" type="hidden" name="id">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" aria-label="Left Align">
<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Gravar
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</form>
</div>
</div>
<div class="modal fade" id="deletar_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<span class="glyphicon glyphicon-trash"></span> Exclusão
</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</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) {
$("#list").find("tbody").append(
"<tr>" +
"<td>" + i.pais + "</td>" +
"<td>" + i.nome + "</td>" +
"<td>" + i.empresa + "</td>" +
"<td align='center'><a class='btn btn-primary glyphicon glyphicon-pencil' title='Editar' id='edit_link' href='" + JSON.stringify(i) + "'></a> | <a class='btn btn-danger glyphicon glyphicon-trash' title='Deletar' id='delete_link' href='" + JSON.stringify(i) + "'></a></td>" +
"</tr>"
);
});
}
});
}
$("#list").delegate('#edit_link', 'click', function (e) {
e.preventDefault();
var info = JSON.parse($(this).attr("href"));
var $modal = $("#editar_modal");
$modal.find("#pais_input").val(info.pais);
$modal.find("#nome_input").val(info.nome);
$modal.find("#empresa_input").val(info.empresa);
$modal.find("#id_input").val(info.id);
$modal.modal('show');
});
update_list();
$('#submit_form').submit(function () {
$.ajax({
url: "inserir.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#inserir_modal');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
$('#edit_form').submit(function () {
$.ajax({
url: "editar.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#inserir_modal');
$("#editar_modal").modal('hide');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
</script>
edit.php
<?php
require('conexao.php');
$id = $_POST['id'];
$pais = $_POST['pais'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";
$update = mysql_query($query);
if ($update) {
$res['response'] = true;
$res['message'] = "Registro atualizado com sucesso!";
} else {
$res['response'] = false;
$res['message'] = "Erro: " . $query . "<br>" . mysql_error();
}
echo json_encode($res);
?>
get_list.php
<?php
require('conexao.php');
$sql = "SELECT id, pais, nome, empresa FROM tb_visitas";
$table = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($table) > 0) {
$res['response'] = true;
while($row = mysql_fetch_assoc($table)) {
$res['results'][] = $row;
}
} else {
$res['response'] = false;
$res['message'] = "Erro: " . $sql . "<br>" . mysql_error($con);
}
echo json_encode($res);
?>
deletar.php
<?php
require('conexao.php');
$id = $_POST['id'];
$query = "DELETE FROM tb_visitas WHERE id = $id ";
if (mysql_query($query)) {
$res['response'] = true;
$res['message'] = "Registro deletado com sucesso!";
} else {
$res['response'] = false;
$res['message'] = "Erro: " . $query . "<br>" . mysql_error($con);
}
echo json_encode($res);
?>
and conexao.php
<?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");
?>
So, now I'd like to put a checkbox in each item for being able to select several records and delete them at once. Another question, when I edit a record if I put a text the field it's filled, but if I put a select it doesn't work. The idea is the select field has all options of countries and letting that item from the record already selected. I hope you understand what I need. Thanks.
From what I understand, you have two questions:
How to put checkboxes on your CRUD list in order to delete all items at once.
It seems that you are using update_list() to load all items on your table. Since thats the case, you need to add an extra <td> in that row to that iteration with the checkbox element.
data.results.forEach(function (i) {
$("#list").find("tbody").append(
"<tr>" +
"<td><input class='item_checkbox' type='checkbox'/></td>" +
"<td>" + i.pais + "</td>" +
"<td>" + i.nome + "</td>" +
"<td>" + i.empresa + "</td>" +
"<td align='center'><a class='btn btn-primary glyphicon glyphicon-pencil' title='Editar' id='edit_link' href='" + JSON.stringify(i) + "'></a> | <a class='btn btn-danger glyphicon glyphicon-trash' title='Deletar' id='delete_link' href='" + JSON.stringify(i) + "'></a></td>" +
"</tr>"
);
});
Once you have that set, you can then use jquery to collect all checkboxes by class .item_checkbox and run a delete function.
How to make sure the SELECT country field is pre-selected when you EDIT an item
Since you are using bootstrap modals, when you edit an item, that modal will popup showing that info. What you need to do is send that item's country ID to that modal's form so that it can be preselected, so do the following change:
first in #editar_modal
<div class="form-group">
<label class="control-label">País:</label>
<select id="pais_input" name="pais">
<?php foreach ($array_pais as $pais) { ?>
<option value="<?php echo $pais ?>"><?php echo $pais ?></option>
<?php } ?>
</div>
then in '#edit_link', 'click', function (e) add:
$modal.find("#pais_input").val(info.pais);