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);
Related
Im trying to solve this problem for few hours already im trying to fetch a data from database into modal to update it but im having difficulty in fetching the data when i click the button that will trigger to display the modal it doesnt show i tried many things already this is my code
Script
function show_profile(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('pages/profile_data')?>',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>' +
'<th>'+'Faculty Name : '+ '</th>' + '<td>' + data[i].faculty_name+'</td>'+ '</tr>' + '<tr>' +
'<th>'+'Faculty Type : '+ '</th>' + '<td>' + data[i].faculty_type+'</td>'+ '</tr>' + '<tr>' +
'<th>'+'Email Address : '+ '</th>' + '<td>' + data[i].email_address+'</td>'+ '</tr>' + '<tr>' +
'<th>'+'Department Name: '+ '</th>' + '<td>' + data[i].department_name+'</td>'+ '</tr>' + '<tr>'+
'Edit'+' '+
'<th>'+'Update' + '</th>' + '</tr>';
}
$('#show_data').html(html);
}
});
}
$('#show_data').on('click','.item_update',function(){
var faculty_name = $(this).data('faculty_name');
var faculty_type = $(this).data('faculty_type');
var email_address = $(this).data('email_address');
var department_name = $(this).data('department_name');
$('#Modal_update_info').modal('show');
$('[name="faculty_name_edit"]').val(faculty_name);
$('[name="faculty_type_edit"]').val(faculty_type);
$('[name="email_address_edit"]').val(email_address);
$('[name="department_name_edit"]').val(department_name);
});
$('#btn_update').on('click',function(){
var faculty_name = $('#faculty_name_edit').val();
var faculty_type = $('#faculty_type_edit').val();
var department_name = $('#department_name_edit').val();
var email_address = $('#email_address_edit').val();
$.ajax({
type : "POST",
url : "<?php echo site_url('pages/update_profile')?>",
dataType : "JSON",
data : {faculty_name:faculty_name, faculty_type:faculty_type, department_name:department_name, email_address:email_address },
success: function(data){
$('[name="faculty_name_edit"]').val("");
$('[name="faculty_type_edit"]').val("");
$('[name="department_name_edit"]').val("");
$('[name="email_address_edit"]').val("");
$('#Modal_update_info').modal('hide');
show_profile();
}
});
return false;
});
Model
public function profile_list()
{
$faculty_name = $this->session->userdata('faculty_name');
$query = $this->db->select('*')
->from('faculty')
->where('faculty_name', $faculty_name)
->join('department','department.department_id = faculty.department_id')
->get();
return $query->result();
}
function update_profiledata(){
$faculty_name = $this->input->post('faculty_name');
$faculty_type = $this->input->post('faculty_type');
$department_name = $this->input->post('department_name');
$email_address = $this->input->post('email_address');
$this->db->where('faculty_name', $faculty_name);
$result = $this->db->update('faculty');
return $result;
}
Controller
public function profile_data()
{
$data = $this->page_model->profile_list();
echo json_encode($data);
}
public function update_profile()
{
$data = $this->page_model->update_profiledata();
echo json_encode($data);
}
View
<div class="card-header p-3 mb-2 bg-dark text-white text-align:center">
My Profile
</div>
<div class="card-body">
<table class="table table-striped" id="mydata">
<tbody id="show_data" style="text-align:left">
</tbody>
</table> </div>
<form>
<div class="modal fade" id="Modal_update_info" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update User Information</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-6 col-form-label"><b>Faculty Name</b></label>
<div class="col-md-6">
<input type="text" name="faculty_name_edit" placeholder="faculty_name" id="faculty_name_edit" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-md-6 col-form-label"><b>Faculty Type</b></label>
<div class="col-md-6">
<input type="text" name="faculty_type_edit" id="faculty_type_edit" class="form-control" placeholder="faculty_type" readonly>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-6 col-form-label"><b>Department</b></label>
<div class="col-md-6">
<input type="text" name="department_name_edit" id="department_name_edit" class="form-control" placeholder="department_name" readonly>
</div>
</div>
<div class="form-group row">
<label class="col-md-6 col-form-label"><b>Email</b></label>
<div class="col-md-6">
<input type="text" name="email_address_edit" id="email_address_edit" class="form-control" placeholder="email_address" required="email ">
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" type="submit" id="btn_edit" class="btn btn-primary">Update</button>
</div>
</div>
</div>
</div>
</form>
Im really confused now please help
... This is the edit/update part which you will edit chosen user. The problem is i think $row or array is empty. The problem is that part. Im accepting any advice to my code to make it better.
Output
This is the output when i click edit button
update.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="uprec.php">
<?php
if(isset($_POST["borrower_id"])){
$output = '';
$connect = mysqli_connect("localhost", "root", "", "librarydb");
$query = "SELECT * FROM tbl_books WHERE id = '".$_POST["borrower_id"]."'";
$result = mysqli_query($connect, $query);
echo "Connected ";
while($row = mysqli_fetch_array($result)){
echo "fetch success";
}
echo "fetch failed";
}
else{
echo "Not Connected";
}
?>
<input type="submit" name="update" id="update" value="UPDATE" class="btn btn-success" />
</form>
</body>
</html>
database.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="script/livesearch.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<a class="navbar-brand" href="#">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Books</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Transactions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Accounts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="logout.php">Logout</a>
</li>
</ul>
</div>
</nav>
<?php
if(!empty($_SESSION)) {
?>
<div class="container p-3">
<h1 class="">Library Database</h1>
<hr><br>
<form>
<div class="input-group ">
<div class="input-group-prepend">
<span class="input-group-text">Search</span>
</div>
<input type="text" name="search_text" id="search_text" class="form-control" />
</div>
</form>
<br />
<button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#addbook_modal">Add Book</button>
<div id="result"></div>
</div>
<hr>
<?php
}else echo '<div class="alert alert-danger alert-dismissible fade show">
<strong>Login Required!</strong> You needed to be login first before you can access the database.
Go back to login
</div>';
?>
</body>
</html>
<script>
$(document).ready(function() {
$('#addbook_form').on("submit", function(event) {
event.preventDefault();
if ($('#booktitle').val() == "") {
alert("Book Title is required");
} else if ($('#category').val() == '') {
alert("Category is required");
} else if ($('#author').val() == '') {
alert("Author is required");
} else if ($('#publishername').val() == '') {
alert("Publisher Name is required");
} else if ($('#datepublished').val() == '') {
alert("Date Published is required");
} else if ($('#copies').val() == '') {
alert("Copies is required");
} else {
$.ajax({
url: "insert.php",
method: "POST",
data: $('#addbook_form').serialize(),
beforeSend: function() {
$('#addbtn').val("Inserting");
},
success: function(data) {
$('#addbook_form')[0].reset();
$('#addbook_modal').modal('hide');
$('#result').html(data);
}
});
}
});
});
$(document).on('click', '#editbtn', function() {
var borrower_id = $(this).attr("id");
$.ajax({
url: "update.php",
method: "POST",
data: {
borrower_id: borrower_id
},
success: function(data) {
$('#borrower_detail').html(data);
$('#editbook_modal').modal('show');
console.log(data);
}
});
});
</script>
<div id="addbook_modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Book</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form method="POST" id="addbook_form">
<div class="form-group">
<label>Book Title:</label>
<input type="text" name="booktitle" id="booktitle" class="form-control" placeholder="Title of the Book">
</div>
<div class="form-group">
<label>Category:</label>
<select name="category" id="category" class="custom-select">
<option>Art</option>
<option>English</option>
<option>Math</option>
<option>Science</option>
<option>Filipino</option>
</select>
</div>
<div class="form-group">
<label>Author:</label>
<input type="text" name="author" id="author" class="form-control" placeholder="Author of the Book">
</div>
<div class="form-group">
<label>Publisher Name:</label>
<input type="text" name="publishername" id="publishername" class="form-control" placeholder="Name of the Publisher">
</div>
<div class="form-group">
<label>Date Published</label>
<input type="date" name="datepublished" id="datepublished" class="form-control" placeholder="Date of Publication">
</div>
<div class="form-group">
<label>Copies</label>
<input type="number" name="copies" id="copies" class="form-control" placeholder="Number of Copies">
</div>
<div class="form-group">
<button id="addbtn" class="btn btn-success">Add</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="editbook_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Book Details</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="borrower_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
fetch.php
<?php
session_start();
include ('connection.php');
if(!empty($_SESSION)) {
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM tbl_books
WHERE booktitle LIKE '%".$search."%'
OR category LIKE '%".$search."%'
OR author LIKE '%".$search."%'
OR copies LIKE '%".$search."%'
OR publishername LIKE '%".$search."%'
OR datepublished LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM tbl_books ORDER BY id DESC
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<thead>
<tr>
<th>Book Title</th>
<th>Category</th>
<th>Author</th>
<th>Publisher Name</th>
<th>Date Published</th>
<th>Copies</th>
<th>Action</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["booktitle"].'</td>
<td>'.$row["category"].'</td>
<td>'.$row["author"].'</td>
<td>'.$row["publishername"].'</td>
<td>'.$row["datepublished"].'</td>
<td>'.$row["copies"].'</td>
<td><button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
}else echo '<div class="alert alert-danger alert-dismissible fade show">
<strong>Login Required!</strong> You needed to be login first before you can access the database.
Go back to login
</div>';
?>
Currently
$_POST["borrower_id"]
is always "editbtn" all the time. So query always returns zero entries.
Your problem is this
<button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
and this should probably something like this
<button type="submit" class="btn btn-success btn-sm" id="editbtn" bookid='.$row['id'].'>Edit</button>
$row['id'] depends on whatever your id field is named.
Also you have to change
var borrower_id = $(this).attr("id");
to
var borrower_id = $(this).attr("bookid");
This should work.
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));
}
Here is my Ajax and what I want is to send a reply into a certain comment but it only works on the last comment that is inserted into the database. I think the model and controller works fine.
$(document).ready(function() {
$('#btn_ReplyComment').click(function(){
var commentReply = $('#commentReply').val();
var ReplyDate = $('#ReplyDate').val();
var commentID = $('#commentID').val();
$.ajax({
type:'POST',
data: {commentReply: commentReply, ReplyDate: ReplyDate, commentID: commentID},
url: '<?php echo site_url('Isidran/Reply_Comment'); ?>',
})
})
});
and my modal
<?php foreach ($showComment as $row): ?>
<div>
<h4><?php echo $row['username'].":" ?> </h4>
<?php echo $row['comDate'] ?><br />
<?php echo $row['comment'] ?><br />
//button to trigger modal
<button id="com_btn_2" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal1<?php echo $row['commentID'] ?>">reply</button>
</div>
<hr> </hr>
//modal to reply into comment only works on the last entered comment
<!-- Modal -->
<div id="myModal1<?php echo $row['commentID'] ?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Reply to this Comment?</h4>
</div>
<div class="modal-body">
<h3><p><?php echo $row['comment'] ?></p></h3>
<h5>Reply:</h5>
<?php $date = date('Y-m-d G:i:s'); ?>
<textarea class="form-control" style="resize:none;" id="commentReply" name="commentReply" maxlength="160" rows="5" cols="50"></textarea>
<input type="hidden" id="ReplyDate" value="<?php echo $date; ?>">
<input type="hidden" id="commentID" value="<?php echo $row['commentID']; ?>">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger" data-dismiss="modal" id="btn_ReplyComment">Send</button>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
controller:
public function Reply_Comment(){
$this->Blog_model->login();
if($this->session->userdata('userID')){
$userID =$this->session->userID;
$username =$this->session->username;
$reply = $this->input->post('commentReply',true);
$commentID = $this->input->post('commentID',true);
$ReplyDate = $this->input->post('ReplyDate',true);
$data['replyComment']=$this->Blog_model->replyComment($commentID, $userID, $username, $reply, $ReplyDate);
} else {
redirect('CodeSmart/loginFail' , 'refresh');
}
}
model:
public function replyComment($commentID, $userID, $username, $reply, $ReplyDate){
if($commentID && $userID && $username && $reply && $ReplyDate){
$query = $this->db->query("INSERT INTO `blog`.`tbl_reply` (comment_id, reply_user_id, reply_username, reply, replydate) VALUES ('$commentID', '$userID', '$username', '$reply', '$ReplyDate')");
}
}
Yes your controller and model there are no issues. The problem is in foreach you are looping that model. There are so many ids with same name like ReplyDate, commentID, etc. So there are no difference with all of them. So in jquery it taking first value. To avoid this problem. You can use like below code
In your view
<?php foreach ($showComment as $row): ?>
<div>
<h4><?php echo $row['username'].":" ?> </h4>
<?php echo $row['comDate'] ?><br />
<?php echo $row['comment'] ?><br />
//button to trigger modal
<button id="com_btn_2" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal1<?php echo $row['commentID'] ?>">reply</button>
</div>
<hr> </hr>
//modal to reply into comment only works on the last entered comment
<!-- Modal -->
<div id="myModal1<?php echo $row['commentID'] ?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Reply to this Comment?</h4>
</div>
<div class="modal-body">
<h3><p><?php echo $row['comment'] ?></p></h3>
<h5>Reply:</h5>
<?php $date = date('Y-m-d G:i:s'); ?>
<textarea class="form-control" style="resize:none;" id="commentReply<?php echo $row['commentID'] ?>" name="commentReply" maxlength="160" rows="5" cols="50"></textarea>
<input type="hidden" id="ReplyDate<?php echo $row['commentID'] ?>" value="<?php echo $date; ?>">
<input type="hidden" id="commentID<?php echo $row['commentID'] ?>" value="<?php echo $row['commentID']; ?>">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger" data-dismiss="modal" id="btn_ReplyComment" onclick="add_comment(<?php echo $row['commentID'] ?>); ">Send</button>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
And your script
<script type="text/javascript">
function add_comment(id) {
var commentReply = $('#commentReply'+id).val();
var ReplyDate = $('#ReplyDate'+id).val();
var commentID = $('#commentID'+id).val();
$.ajax({
type:'POST',
data: {commentReply: commentReply, ReplyDate: ReplyDate, commentID: commentID},
url: '<?php echo site_url('Isidran/Reply_Comment'); ?>',
})
}
</script>
It will work as you expected.
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.