Adding and deleting with ajax - php

I'm trying to add and delete data to the database using ajax and php.
Everything works nice. But the problem is if I delete the last item and then try to add a new one, only the first one can be added, the second one, third one... are also added to the databse, but they are not shown on the page. I can see those only when I refresh the page.
My code for delete and add :
Add :
<!--Dodavanje texta-->
<script type="text/javascript">
//Dodavanje texta
$(document).ready(function () {
$(document).on("click", "#btnAddText", function(e){
var title = $("#txtTitle").val();
var text = $("#txtText").val();
$.ajax({
url : "add-text.php",
type : "POST",
dataType:"json",
data : {title:title, text:text},
beforeSend: function(){
$("#btnAddText").text("Saving...");
},
success: function(msg){
if(msg.br_rez == 1){
$(".sadrzaj").append(msg.result);
$("#natpisPrazno").fadeOut(300);
$("#txtTitle").val("");
$("#txtText").val("");
$("#btnAddText").text("Save");
$("#brRez").text(msg.br_rez);
}else{
$("#example1").append(msg.result);
$("#txtTitle").val("");
$("#txtText").val("");
$("#btnAddText").text("Save");
$("#brRez").text(msg.br_rez);
}
},
error: function(){
$("#error").text("Error! Something is wrong, the text is not saved!").fadeIn(300);
}
});
e.preventDefault();
});
});
</script>
Delete :
<!-- Brisanje texta -->
<script type="text/javascript">
$(document).ready(function() {
//Brisanje texta
$(document).on("click", ".btnDelText", function(){
var cijeliID = this.id.split("-");
var id = cijeliID[1];
$.ajax({
url : "text-delete.php",
type: "POST",
data : {id : id},
beforeSend: function(){
$("#delText-"+id).text("Deleting...");
},
success: function(msg){
if(msg){
if(msg == 0){
$(".divSadrzaj").fadeOut(300);
$("#natpisPrazno").addClass("alert-warning");
$("#natpisPrazno").fadeIn().html("Er zijn nog geen texten!");
}else{
$("#textItem-"+id).fadeOut(800);
$("#brRez").text(msg);
}
}else{
$("#errorDel").addClass("btn-danger");
$("#errorDel").text("Something was wrong!");
}
},
error: function(){
$("#errorDel").addClass("btn-danger");
$("#errorDel").text("Something was wrong!");
}
});
});
});
</script>
And the table where the databse data is shown is :
<div class="content">
<!-- Main row -->
<div class="row">
<div class="col-md-12 sadrzaj">
<?php
$rez = mysqli_query($kon, "SELECT * FROM texts");
$brRez = mysqli_num_rows($rez);
if($brRez < 1){
echo "<div class=\"alert alert-warning\" role=\"alert\" style=\"text-align:center;\">
Er zijn nog geen texts!
</div>";
}else{
echo "<div id=\"natpisPrazno\" class=\"alert\" role=\"alert\" style=\"text-align:center;\">
</div>";
?>
<div class="box divSadrzaj">
<div class="box-title">
<h3>Totaal texts - <span id="brRez"><b><u><?php echo $brRez; ?></u></b></span></h3>
</div><!-- /.box-title -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Text</th>
<th>Acties</th>
</tr>
</thead>
<tbody>
<?php
while($red = mysqli_fetch_assoc($rez)){
echo "<tr id=\"textItem-". $red["id"] ."\">
<td style=\"text-align:center;\">". $red["id"] ."</td>
<td style=\"text-align:center;\">". $red["title"] ."</td>
<td style=\"text-align:center;\">". $red["text"] ."</td>
<td style=\"text-align:center;\">
<a class=\"btn btn-danger btn-sm btnDelText\" title=\"". $red["title"] . "-wissen\" id=\"delText-". $red["id"] ."\">
<i class=\"fa fa-trash-o \"></i>
</a>
<a class=\"btn btn-success btn-sm\" title=\"". $red["title"] . "-veranderen\" >
<i class=\"fa fa-pencil-square-o\"></i>
</a><br/><br/>
<div id=\"errorDel\"></div>
</td>
</tr>";
}
?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Title</th>
<th>Text</th>
<th>Acties</th>
</tr>
</tfoot>
</table>
</div>
</div><!-- /.box -->
<?php
}
?>
</div><!-- /.col -->
</div><!-- /.row -->
</div>
Thus everything works great if there is no data in the database and I try to add a new one, it is added to the database and shown on the page. The first one, second one..every record is added and shown. Then when I try to delete it, it works also very nice.
Only when I delete the last record, then I can add only one new record that is shown on the page. The second one is also added to the database but it is not shown on the page until I refresh the page.
Any ideas? Thanks.
UPDATE
When I add $(".sadrzaj") to the console I get :
When I add $(".sadrzaj").append('test'); to the cosole I get (it is shown):
When I try to add a new record, I get next response (exactly what I need to get, table row to append to the table, but it is not shown)
And then when I refresh the page I get it right :

Related

echoing a php file into a modal that is inside a modal | PHP

I have this php page. I'm struggling to find a solution to this one as whenever I call this page inside a modal, it does not show.
I tried several changes to this one, like changing the quotations of ever single elements inside the code, changing the echoing structure, and modifying to all just for me to be able to echo it, but no luck in all of them.
This serves as my earnings_amendment_table.php
<?php include 'backend/session.php'; ?>
<?php
if(isset($_POST['referenceno']))
$id=$_POST['referenceno'];
$sql = "select credit, debit, referenceid, datedue,
referenceno, earningsamendment.employeeidno, earningsamendment.accounttitle, earningsamendment.postedby, approvedby,
notedby,employeemasterfile.lastname,employeemasterfile.firstname,employeemasterfile.middlename,
earningsamendment.particulars,earningsamendment.accounttype
from earningsamendment
left join employeemasterfile on earningsamendment.employeeidno= employeemasterfile.employeeidno
where referenceno='$id' order by datedue desc";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$out = "
<div class='box-body'>
<table id='earnings_amendment_view' class='table table-bordered' style='table-layout: fixed; display: table'>
<thead>
<th></th>
<th>Reference ID.</th>
<th>Reference No.</th>
<th>Employee Name</th>
<th>Account Title</th>
<th>Amount</th>
<th>Activity</th>
<th>Posted By</th>
<th>Validated By</th>
<th>Noted By</th>
<th>Tools</th>
</thead>
<tbody>
";
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr data-key-1=".$row['particulars']." data-key-2=".$row['accounttype']." data-key-3=".$row['datedue'].">
<td class='details-control'></td>
<td>".$row['referenceid']."</td>
<td>".$row['referenceno']."</td>
<td>".$row['lastname']." ".$row['middlename']." ".$row['firstname']."</td>
<td>".$row['accounttitle']."</td>
<td>".$row['credit']."</td>
<td>".(($row['debit']==$row['credit']) ? 'PAID' : 'FOR TAKE UP' )."</td>
<td>".$row['postedby']."</td>
<td>".$row['approvedby']."</td>
<td>".$row['notedby']."</td>
</tr>
";
}
$out .= '
</tbody>
</table>
</div>
';
echo $out;
?>
This script is being called by this modal caller from earnings_amendment.php
$(function(){
$("body").on('click', '.edit', function (e){
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'earnings_amendment_table.php',
data: {referenceno:id}
}).done(function(d){
//console.log('d: '+d);
$('#earnings_amendment_table_').html(d);
$('#earnings_amendment_table_').show();
});
});
});
Along with the clicker, still within the same page (earnings_amendment.php)
$("body").on('click', '.select', function (e){
e.preventDefault();
$('#select').modal('show');
var id = $(this).data('id');
getRow(id);
$(".modal:visible").modal('toggle');
});
This is the table
function format ( dataSource ) {
var html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;" class="table table-bordered">';
for (var key in dataSource){
html += '<tr>'+
'<td>' + key +'</td>'+
'<td>' + dataSource[key] +'</td>'+
'</tr>';
} return html += '</table>'; }
var earnings_amendment_employee_view_table = $('#earnings_amendment_view').DataTable({});
$('#earnings_amendment_view').on('click', 'td.details-control', function () { var tr = $(this).closest('tr');
var row = earnings_amendment_employee_view_table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format({
'Particulars : ' : tr.data('key-1'),
'Account Type : ' : tr.data('key-2'),
'Date Due : ' : tr.data('key-3')
})).show();
tr.addClass('shown');
} });
And, this is the modal where it is being called.
This is earnings_amendment_modal.php
<!-- Edit -->
<div class="modal fade" id="edit">
<div class="modal-dialog" style="width:95%">
<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"><b>Update Founder Data</b></h4>
</div>
<div class="modal-body">
<form autocomplete='off' class="form-horizontal" method="POST" action="earnings_amendment_edit.php">
<input type="hidden" class="decid" name="id">
<input type="hidden" name="year" value="<?php echo $year; ?>">
<input type="hidden" name="accounttitle" value="<?php echo $accounttitle; ?>">
<input type="hidden" class="decid" name="id">
<!-- Table Loader -->
<div class="form-group" id="earnings_amendment_table_"><div class="col-sm-9" id="earnings_amendment_table_" style="width:100%">
</div></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
</form>
</div>
</div>
</div>
</div>
What seems to be the problem here? As my modal caller is properly set up.
<!-- Table Loader -->
<div class="form-group" id="earnings_amendment_table_"><div class="col-sm-9" id="earnings_amendment_table_" style="width:100%">
</div></div>
It's only displaying this.
I tried to check it via purposely doing errors in the table and the error properly displays.
I'm assuming that the main cause of this concern is this line.
echo "
<tr data-key-1=".$row['particulars']." data-key-2=".$row['accounttype']." data-key-3=".$row['datedue'].">
<td class='details-control'></td>
<td>".$row['referenceid']."</td>
<td>".$row['referenceno']."</td>
<td>".$row['lastname']." ".$row['middlename']." ".$row['firstname']."</td>
<td>".$row['accounttitle']."</td>
<td>".$row['credit']."</td>
<td>".(($row['debit']==$row['credit']) ? 'PAID' : 'FOR TAKE UP' )."</td>
<td>".$row['postedby']."</td>
<td>".$row['approvedby']."</td>
<td>".$row['notedby']."</td>
</tr>
";
As I already have a variable holder $out that should hold everything together.
Is there a turnaround for this? Thanks in advance.

Add record to MySQL using AJAX / jquery on multiple elements with the same class

Im new here and I have some difficulties to make my code to work. Hope u guys can help me. Im displaying records form MySQL in a modal box in a table format. Each row has its own add (+) button generated via php loop which displays records that should be leter on, added to a different table using jquery on click event and AJAX. Each td row is provided with an input field with class name "idKont", but only the first one will be added after I click on the + / add button.
$('#add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); // ID of the customer that will be passed
var idKont = $('.idKont').val(); // ID of the contact person
$.ajax ({
url: "folder/insert_data.php",
method:"POST",
data:
{
id: ptId,
idKont: idKont
},
dataType:'text',
success: function(result) {
//$('#myModal').modal('hide');
$('#alert_modal').append( '<div class="alert alert-success">Success</div>' ).fadeIn(1000).fadeOut(4000);
}
})
})
and this is the HTML Code with PHP:
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:10px 50px;">
<p><span class="glyphicon glyphicon-lock"></span> Choose Contact Person</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" style="padding: 40px 50px;">
<form role="form" method="post">
<div id="alert_modal"></div>
<table class="table table-responsive">
<thead class="thead-light">
<tr>
<th>ID</th>
<th>Vorname</th>
<th>Name</th>
<th>Tel</th>
<th>Mobil</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $connser->prepare("SELECT ID, Vorname, Name, Tel, Mobil FROM Contactperson ORDER BY ID DESC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$kontID = $row['ID'];
?>
<tr>
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Vorname']; ?></td>
<td><?php echo $row['Name']; ?></td>
<td><?php echo $row['Tel']; ?></td>
<td><?php echo $row['Mobil']; ?></td>
<td><input class="idKont" value="<?php echo $kontID; ?>" type="hidden" /></td>
<td><button type="submit" class="btn btn-success add_kontpers">+</button></td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error";
//echo "Error: " . $e->getMessage();
exit;
}
?>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
The modal box stays open and it shoud be, but if I click the first element on the top, then only this one will be added. I would like to have the oportunity to click for example one position on the list to add it to the table, the the second one, and so on, but if I click other butten then the first one then the modalbox will be closed and the website reloads. Any help or pinting in the right direction will be highly appreciated.
Two things, first you can't reuse the same ID and by having add_kontpers in a loop, you will reusing that.
So first, change that to a class and idAj doesn't exist in the provided code.
<button type="submit" class="btn btn-success add_kontpers">
Then make this change in your jQUERY
$('.add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); ?????????????????????
var idKont = $(this).parents("tr").find('.idKont').val(); // ID of the contact person
Javascript
$(document)
.on('click', 'button#add_kontpers', function(a){
a.preventDefault();
var button = $(this);
var row = button.closest('tr');
var id = row.find('input').val();
$.post("folder/insert_data.php", {id : id, idKont : id})
.done(function(response){
//Your response
})
})

AJAX: sending xmlhttp request in PHP loop but result is not dynamic

I have a table that is given based on the option selected in a . This table generates list of students based on class selected. I want a dynamic modals popup each time the SMS button on a student row is clicked it is suppose to show the related parent's name dynamically. It's actually doing this but the issue is it is not dynamic one i refresh the page the data for the first student button clicked is what shows as response for every other one. until i refresh again. I select another and it shows thesame for every other student
Though when i used develop tool(network) in browser the xmlrequest was sent sucessfully and the interesting thing is the passed "id" param for the selected student is correct. but it just showing the same one that's selected first in the modal popup after refresh
the code looks like this
`
function smsmodal(id){
var data= {"id" : id};
jQuery.ajax({
url : '/sms/include/smsmodal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#sms-modal').modal('toggle');
},
error: function(){
alert("Something went wrong")
}
});
}
`
And for the loop:
<?php
require_once '../../service/mysqlcon.php';
$parentID = $_POST['parentID'];
$selected = sanitize($_POST['selected']);
$studentquery = $conn->query("SELECT * FROM students WHERE class = '$parentID' ORDER BY lastname");
$count = mysqli_num_rows($studentquery);
$i = 1;
ob_start(); ?>
<?php
if($count < 1){
?>
<br><br>
<h4 class="text-warning text-center bg-warning" style="padding:20px">No student has been registered in this class.</h4>
<?php
}else{
?> ...... other html..
<div class="table-responsive">
<table class="table table-hover">
<thead><th><input type="checkbox"> Roll</th><th>Photo</th><th>Student Name</th><th>Address</th><th>Actions</th></thead>
<tbody>
<?php while($s = mysqli_fetch_assoc($studentquery)) :?>
<tr>
<td><input type="checkbox"> <?=$i;?></td>
<td> <img src="<?=$s['photo'];?>" alt="photo" class="img-responsive" id="photo"></td>
<td><?php echo $s['lastname'].' '.$s['firstname'];?></td>
<td><?=$s['address'];?></td>
<td><button class="btn btn-success btn-xs" type="button" onclick="smsmodal(<?=$s['id']; ?>)" style="width:80px"><span class="fa fa-mobile"></span> SMS</button> </td>
</tr>
<?php $i++;?>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php } ?>
<?php echo ob_get_clean(); ?>

Sweetalert with delete action into database

Im using bootstrap template. In table I have delete button, clicking on it, Im able to display a confirmation message with swal. But after clicking yes,delete it.... it has perform action by deleting from database. Please guide me how to write a query in swal so that it takes that particular row id and delete that row into database.
deleting action should be like
if(isset($_POST['delete'])) {
$update=$_POST['v_id'];
mysqli_query($conn, "UPDATE vendor_pricing SET status = 'deleted' where Vendor_pricing_id=$update");
}
<?php
session_start();
if(empty($_SESSION))
{
header("Location: ../login.php");
}
$mpage = "printer";
$page = "list_printer.php";
include '../header.php';
$email1 = $_SESSION['email'];
$Vendor_id="SELECT Vendor_id FROM vendors where email = '$email1' ";
$result=mysqli_query($conn,$Vendor_id);
$row = mysqli_fetch_row($result);
$sql = "SELECT Vendor_pricing_id, status, printer_name,process,material,color,strength,surface_finish,per_gram_charge,per_hour_charge FROM vendor_pricing where Vendors_Vendor_id= $row[0] and status='active' or status='inactive' ";
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<!DOCTYPE html>
<html>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Printer Lists
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Printer</li>
<li class="active">List Printers</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box table-responsive no-padding">
<div class="box-header">
<h3 class="box-title">List of all Printers</h3>
</div>
<!-- /.box-header -->
<div id="response" class="box-body">
<table id="example1" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th width="8%">Printer Name</th>
<th>Process</th>
<th>Material</th>
<th>Color</th>
<th>Strength</th>
<th>Surface Finish</th>
<th padding>per Gram</th>
<th>per Hour</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($query))
{
$vid=$row['Vendor_pricing_id'];
$p_name=$row['printer_name'];
$pro=$row['process'];
$mat=$row['material'];
$color=$row['color'];
$type=$row['strength'];
$sur=$row['surface_finish'];
$p_gram=$row['per_gram_charge'];
$p_hour=$row['per_hour_charge'];
$st=$row['status']; if ($st=="active"){ $link='inactive'; $color1='success'; $style='white'; $cursor='allowed'; $tip="inactive ur printer";}
else { $link='active';$color1='warning'; $style='#EEE'; $cursor='not-allowed'; $tip="activate ur printer";}
?>
<tr style="background-Color:<?php echo $style;?>; cursor: <?php echo $cursor;?>;">
<form method="post">
<td><?php echo $vid;?>
<input type="hidden" value="<?php echo $vid;?>" name="v_id">
</td>
<td><?php echo $p_name;?></td>
<td><?php echo $pro;?></td>
<td><?php echo $mat;?></td>
<td><?php echo $color;?></td>
<td><?php echo $type;?></td>
<td><?php echo $sur;?></td>
<button type="delete" name="delete" value="<?php echo $vid;?>" id="<?php echo $vid ?>" type="submit" class="btn-warning" onclick="archiveFunction(this.id)">Delete</button>
</td>
</tr>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
$('#reloadpage').click(function() {
location.reload(true);
});
function archiveFunction(id) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Delete it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
window.location.href="delete.php?delete_id="+id;
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
});
}
</script>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
</div>
</html>
You are getting the v_id from post variables in php, but you are actually requesting the server with get method. This is the reason why it is not working. The proper way is to request the server with post method to perform delete action.
You should change this snippet from:
if (isConfirm) {
// this is `get` request to the server
// so you can only get the data from $_GET variable, says $_GET['delete_id']
window.location.href = "delete.php?delete_id=" + id;
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
TO
if (isConfirm) {
// this is `post` request to the server
// so you can get the data from $_POST variables, says $_POST['delete'] $_POST['v_id']
$.ajax({
method: 'POST',
data: {'delete': true, 'v_id' : id },
url: 'delete.php',
success: function(data) {
}
});
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
You can create AJAX request like this:
$.ajax({
method: 'GET',
data: {'id' : this.id },
url: 'delete.php',
success: function(data) {
// Request is successful you have the response in data
}
})
$(document).on('click', '.delete', function () {
var id = $(this).data('id');
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
}).then((result) => {
if (result.value) {
$.ajax({
url: 'delete.php?action=delete',
type: 'POST',
data: 'id=' + id,
dataType: 'json'
})
.done(function (response) {
swal('Deleted!', response.message, response.status);
fetch();
})
.fail(function () {
swal('Oops...', 'Something went wrong with ajax !', 'error');
});
}
})
});

How do i get the details of person who is selected in drop down?

I am building a CI application. here i show the Login and Logout of Employees. now i have a drop down where i fetch all the users from database and below that i have a table that shows the all users and their relevant login logout. Now i want to do something like when i select a user from drop down i can seen only his information and not all others.
The Controller:
public function index()
{
$this->data['attendances'] = $this->attendance_m->join_data();
$this->data['attendance_dropdown'] = $this->attendance_m->get_emp_list();
$this->data['subview'] = 'admin/attendance/index';
$this->load->view('admin/_layout_main', $this->data);
}
The Model:
function get_emp_list() {
$q = $this->db->select('name')
->from('users')
->get();
return $q->result_array();
}
Below is my code to fetch the users:
<script type="text/javascript" src="<?php echo site_url('js/bootstrap.min.js');?>"></script>
<h2>Upload CSV To Import Users</h2>
<!-- in the action you need to place /controller/function in our case #Attendance, #upload -->
<form method="post" action="<?php echo site_url('admin/attendance/upload');?>" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<br>
<input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
</form>
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<h1><label for="sel1">Select list:</label></h1>
<select name="attendance-list" id="attendance-list" class="form-control" >
<?php foreach($attendance_dropdown as $value) { ?>
<option value="<?php echo $value['name'];?>"><?php echo $value['name']; ?> </option>
<?php } ?>
</select>
</div>
<h1 class="page-header">Attendance Details</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
All Calls Records
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Date</th>
<th>Entry</th>
</tr>
</thead>
<tbody>
<?php if(count($attendances)): foreach($attendances as $attendance): ?>
<tr class="odd gradeX">
<td><?php echo trim($attendance->emp_id,'">'); ?></td>
<td><?php echo trim($attendance->name.$attendance->last_name,'">'); ?></td>
<td><?php echo trim($attendance->date_data,'">'); ?></td>
<td><?php trim($attendance->entry,'">'); ?> <?php if($attendance->entry >100)
{
echo "Logged In";
}
else
{
echo"Logged Out";
}?>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">We could not find any Data.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<!-- /.row -->
<!-- jQuery -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- DataTables JavaScript -->
<script src="../bower_components/datatables/media/js/jquery.dataTables.min.js"></script>
<script src="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>
You have to bind on change event for given dropdown if value is not empty the call ajax and get info of that particular user
in you js :
<script>
site_url="http://localhost/ci_root/index.php/";
$('#attendance-list').on('change', function () {
var select_emp_name=$(this).val();
if(select_emp_name!=""){
var params={};
params["name"]= select_emp_name;
$.ajax({type: 'POST', url: site_url + 'employee/getUserInfo', data: params,success: function (response) {
//write on response logic/set employee details
var user_data=JSON.parse(response);
}, async: true});
}
})
</script>
in Controller function
public function getUserInfo()
{
$name=$this->input->post("name",true);
$data = $this->attendance_m->get_emp_data($name);
echo json_encode( $data);
exit;
}
in Model Function:
function get_emp_data($name) {
$q = $this->db->select('*')//required fields
->from('users')
->where('name',$name) // considering name is unique field
->get();
return $q->result_array();
}
Suggestion : Its better practice to send user id or unique field for dropdown values instead of name like user_id=>1,name=>sanjay
and we can set user_id as value at dropdown and name as label for option
it will look like
<?php foreach($attendance_dropdown as $value) { ?>
<option value="<?php echo $value['user_id'];?>"><?php echo $value['name']; ?> </option>
<?php } ?>
according your where clause also change
let me know if you need more support
here is your display code for Scipt only
<script>
site_url = "http://127.0.01/project/admin/";
$('#attendance-list').on('change', function() {
var select_emp_id = $(this).val();
if (select_emp_id != "") {
var params = {};
params["id"] = select_emp_id;
$.ajax({type: 'POST', url: site_url + 'attendance/getUserInfo', data: params, success: function(response) {
//write on response logic/set employee details
var user_data = JSON.parse(response);
var row = '<tr class="odd gradeX"><td>' + user_data.emp_id + '</td><td>' + user_data.name + ' ' + user_data.last_name'</td><td>' + user_data.date_data + '</td><td>' + user_data.entry + ' ' + (user_data.entry > 100?"Logged In":"Logged Out") + '</td> </tr>';
$("#dataTables-example tbody").find('tr').remove();
$("#dataTables-example tbody").append(row);
}, async: true});
}
});
</script>
Here is how to grab data in codeigniter with a post:
Controller
function catchPost(){
$this->form_validation->set_rules("nametage", "something", "required");
if($this->form_validation->run() == TRUE){//Formvalidation worked
$this->load->model("model_name");
$data['userInfo'] = $this->model_name->function();
$this->load->view("view", $data);
}else{
redirect("prevUrl", "refresh");
}
}
Model:
function getData(){//No parameters because we work directly with the post. You should filter the post before you actually use it.
$query = $this->db-select("*")
->from("users")
->where("username", $this->input->post("username"))
->get()
->result_array();
return $query
}
This is a general way of grabbing specific data.

Categories