view :
<tr style="background-color:#333; color:#FFFFFF;" align="center">
<td>No</td>
<td>ID TRANS</td>
<td>NAMA</td>
<td>TGL</td>
<td>JUMLAH</td>
<td>STATUS</td>
<td>TOTAL</td>
<td>JENIS PEL</td>
<td>NAMA</td>
<td>PENGELOLAAN</td>
</tr>
<tr class="dataku"></tr>
my jquery in array
<script type="text/javascript">
$(document).ready(function() {
selesai();
});
function selesai() {
setTimeout(function() {
update();
selesai();
}, 200);
}
function update() {
$.getJSON("<?php echo base_url();?>transaksiDigorCont/ambilDataTransaksi", function(data) {
alert("jhjh");
$(".dataku").empty();
$no=1;
$.each(data.result, function() {
$(".dataku").append(
"<td>"+$no+"</td>\n\
<td>"+this['id_transaksi']+"</td>\n\
<td>"+this['nama']+"</td>\n\
<td>"+this['tgl_transaksi']+"</td>\n\
<td>"+this['jumlah']+"</td>\n\
<td>"+this['status_transaksi']+"</td>\n\
<td>"+this['total']+"</td>\n\
<td>"+this['status_pelanggan']+"</td>\n\
<td>"+this['nama_karyawan']+"</td><td>"+this['nama_karyawan']+"</td>");
$no++;});
});
}
data.result have 3 rows, but if show in view all row show in <td>No</td> , I want every index is in the header title , for example : No have value $no, ID TRANS have value this['id_transaksi'] ect
Assuming your json response is Okay, Put this class="dataku" in your your table instead of tr
<table class="dataku">
$(".dataku").append(
"<tr><td>"+$no+"</td>\n\
<td>"+this['id_transaksi']+"</td>\n\
<td>"+this['nama']+"</td>\n\
<td>"+this['tgl_transaksi']+"</td>\n\
<td>"+this['jumlah']+"</td>\n\
<td>"+this['status_transaksi']+"</td>\n\
<td>"+this['total']+"</td>\n\
<td>"+this['status_pelanggan']+"</td>\n\
<td>"+this['nama_karyawan']+"</td><td>"+this['nama_karyawan']+"</td></tr>");
$no++;});
Related
I am trying to fetch data into a table and nothing happens.
No table appears
No data is fetched
Controller
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
$this->load->model("usersmodel");
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
$data['pagetitle']=" -->All Users Using Ajax<--";
foreach ($allu as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
</tr>';
endforeach;
$this->load->view("template/admin/header",$data);
$this->load->view("users/allusersusingajax",$data);
$this->load->view("template/admin/footer");
}
}
jQuery
<script>
$(document).ready(function () {
FetchAllUserUingAjax();
function FetchAllUserUingAjax() {
$.ajax({
url:'<?php echo base_url()?>Users/indexajax',
method:"post",
success:function (data) {
$(".userdataajax table").append(data);
}
})
var action="FetchAllUserUingAjax";
$.ajax({
url:"<?php echo base_url()?>Users/indexajax",
method:"post",
data:{action:action},
success:function (data) {
$(".userdataajax table tr ").not("table tr:first").remove();
$(".userdataajax table").append(data);
Table();
}
})
}
})
</script>
Model
public function ShowAllUsers()
{
$sql=$this->db->get("users");
return $sql->result();
}
View
<div class="userdataajax table-responsive">
<table class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
Your code hints at other relevant code that is not shown. I'm taking what you show as all that needs to be known. Here's what I see based on that premise.
First, the view. Add an id to the table. It makes JQuery selectors so much easier. The JavaScript is in this file which is "users/allusersusingajax.php".
<div class="userdataajax table-responsive">
<table id='user-table' class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
<script>
$(document).ready(function () {
function FetchAllViaAjax() {
$.ajax({
url: '<?= base_url("users/get_all_users") ?>',
method: "post",
dataType: 'html',
success: function (data) {
var table = $("#user-table");
table.not("table tr:first").remove();//your code makes it unclear why you need this
table.append(data);
}
});
FetchAllViaAjax();
}
});
</script>
The controller needs two methods. One to show the table another to get the rows. This is the file Users.php
//show the page which includes the basic <table> and header row
public function indexajax()
{
// The code and question text give no reason for this conditional test
// So I'm removing it
//if($this->input->post("action") == 'FetchAllUserUingAjax')
//{
$data['pagetitle'] = "-->All Users Using Ajax<--";
$this->load->view("template/admin/header", $data);
$this->load->view("users/allusersusingajax");
$this->load->view("template/admin/footer");
//}
}
//respond to ajax request
public function get_all_users()
{
$this->load->model("usersmodel");
$allu = $this->usersmodel->ShowAllUsers("users");
$out = ''; //if the model returned an empty array we still have a string to echo
//using PHP's output buffer to simplify creating a big string of html
ob_start(); //start output buffering
foreach($allu as $a):
?>
<tr><td><?= $a->id; ?></td><td><?= $a->username; ?></td></tr>
<?php
endforeach;
$out .= ob_get_clean(); //append the output buffer to the $out string
echo $out;
}
Read about PHP's Output Control Functions
I'd first update my model to return an array:
return $sql->result_array();
Then in your controller, you don't need to load a view:
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
//set content type
header("Content-type: application/json");
$this->load->model("usersmodel");
echo json_encode(
$this->usersmodel->ShowAllUsers(); //this method doesn't expect an argument, no need to pass one
);
}
}
Then in your ajax callback:
success: function(resp){
$.each(resp, function(k,v){
console.log(v);
});
}
i have a search input field in my page. currently i am displaying data from the database successfully in a table(id="table_userinfo"). Now i want to add the live search functionality to my table(id="table_userinfo") as well. i am using php codeigniter.
in my user_model i have:
function search_userInfo($keyword)
{
$this->db->like('DeviceName',$keyword);
$this->db->or_like('RegistrationDateTime',$keyword);
$this->db->or_like('LastUpdateDateTime',$keyword);
$this->db->or_like('AppVersion ',$keyword);
$this->db->or_like('iOSVersion',$keyword);
$this->db->or_like('DeviceDID',$keyword);
$this->db->or_like('DeviceToken',$keyword);
$query = $this->db->get('userinfo');
if($query)
{
return $query->result();
}
else
{
return NULL;
}
}
in my login_controller:
function displayDatabase()
{
$data['tableInfo']=$this->user_model->fetchData();
$this->load->view('adminPanel_view',$data);
}
function search()
{
$search=$this->input->post('searchString');
$data['tableInfo']=$this->user_model->search_userInfo($search);
}
in my adminPanel_view page, i have:
<script>
$('#search').keyup(function(){
var input_data = {searchString: $('#search').val() };
//console.log(input_data);
$.ajax({
type:"POST",
url:base_url+'index.php/login_controller/search',
data:input_data,
success:function(data){
if(data.length>0)
{
console.log(data);
}
}
});
});
</script>
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>Serial No.</th>
<th class="hidden-xs">Device Name</th>
<th>Device Type</th>
<th>RegistrationDateTime </th>
<th>LastUpdateTime</th>
<th>LastPushNotificationSent</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php //print_r ($tableInfo);exit;?>
<?php $no=0;?>
<?php foreach($tableInfo as $r): ?>
<tr>
<td><?php echo $no ?></td>
<td><?php echo $r->DeviceName ?></td>
<td><?php echo $r->DeviceType ?></td>
<td><?php echo $r->RegistrationDateTime ?></td>
<td><?php echo $r->LastUpdateDateTime ?></td>
<td><?php echo $r->LastPushNotificationSent ?></td>
<td><?php echo "Actions" ?></td>
</tr>
<?php $no+=1;?>
<?php endforeach; ?>
</tbody>
</table>
this is the search bar that i am using in addition to this table
<div id="" class="dataTables_filter">
<label>
<input placeholder="Search" class="form-control input-sm" aria-controls="sample_1" type="text" id="search" name="search_userinfo">
</label>
</div>
how do i display the data that i am getting through the Ajax call and show it in the table(id="search_userinfo).
inside of function search() return it as:
echo json_encode($this->user_model->search_userInfo($search));
and inside of javascript do this
<script>
$('#search').keyup(function(){
var input_data = {searchString: $('#search').val() };
//console.log(input_data);
$.ajax({
type:"POST",
url:base_url+'index.php/login_controller/search',
data:input_data,
dataType: "json",
success:function(data){
$("#table_userinfo").html(" "); //clear everything from table
data.forEach(function(entry) {
$("#table_userinfo").append("<td>"+entry.DeviceName+"</td><td>");
//just add everything here
});
}
});
});
</script>
Your Controller
function search()
{
$search=$this->input->post('searchString');
$data['tableInfo']=$this->user_model->search_userInfo($search);
print_r(json_encode($data['tableInfo']));exit
}
In your ajax add this line
dataType:'json';
Now In Your Success function You will get an json for that data ,You can append like this,
$.each(data, function(i, item) {
alert(item.DeviceName); // append data where you need to append
});
But Please be sure about amount of data you get in success function, with keyup
I need a help with the following code. There are 2 styles: activatedRow and disactivatedRow. When a user clicks on a button (located inside the TD of a table), then either activatedRow or disactivatedRow is applied to a row. Selection of a style is based on current style. For instance, if a row is activated, then the button will disactivate it, and vice versa.
So, I have a problem with AJAX success. How to write IF statement to check current style of a row?
P.S. Also it would be interesting to know how to change TD IMG (button) for disactivated and activated rows.
CSS
.activatedRow td {
background-color:#FFFFFF !important;
color: #000000 !important;
}
.disactivatedRow td {
background-color:#DFE1ED !important;
color: #9896A8 !important;
}
Function "disactivateRow()"
<script type="text/javascript">
function disactivateRow(flightNum,obj){
$.ajax({
type: "POST",
url: "callpage.php?page=tables/disactivate.php",
data: "flightNum=" + flightNum,
success: function(){
if ($(obj).hasClass("activatedRow")) {
$(obj).removeClass("activatedRow").addClass("disactivatedRow");
} else
$(obj).removeClass("disactivatedRow").addClass("activatedRow");
}
});
}
</script>
Button inside the table
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Flt Num</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):
$flightNum=$row['flightNum'];
?>
<tr id="<?php echo $flightNum; ?>" class="edit_tr">
<td><?php echo $flightNum;?></td>
<td id="<?php echo $flightNum; ?>">
<div onclick='disactivateRow("<?php echo $flightNum; ?>", this)'>
<img src='images/disactivate.png' alt='Disactivate' />
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
jQuery DataTable activation
$(document).ready(function(){
$('#newspaper-b').dataTable({
"sPaginationType":"full_numbers",
"bJQueryUI":true,
'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (aData[0] == "0") {
nRow.className = "disactivatedRow";
} else
nRow.className = "activatedRow";
return nRow;
}
});
ANSWER:
It works now:
$(".disact_but" ).click(function() {
var ID=$(this).attr('id');
$.ajax({
type: "POST",
url: "callpage.php?page=tables/disactivate.php",
data: "flightNum=" + ID,
success: function(){
$("#"+ID).toggleClass("disactivatedRow", 100);
}
});
return false;
});
If obj is the TD to apply the style as your code indicates you could use toggleClass
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
$(obj).closest('tr').toggleClass('disactivatedRow');
$(obj).closest('tr').toggleClass('activatedRow');
EDIT
According new information you added, obj is a row's child. closest method should give you the appropiate tr and then we can apply toggleClass
how to display this json file using jquery?
[ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" },
{ "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
and look like this
<table>
<thead>
<tr>
<th>code</th> <th>lastname</th> <th>firstname</th>
</tr>
</thead>
<tbody>
<tr>
<td>00-002159</td> <td>SALUNGA </td> <td>JEFFERSON</td>
<td>00-002160 </td> <td>TUMANAN </td> <td>RHODA</td>
</tr>
</tbody>
</table>
jQuery.template should be a good approach to show the data.
Parse json data, the data what you mention in example is array of objects
var data = [ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" },
{ "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
[] - Represents js array an {} - Represents js Object So to parse data and get RHODA use data[0].firstname;
You could try this...
<script type='text/javascript'>
var data = [ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" }, { "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ];
var string = "";
$.each(data, function() {
$.each(this, function(k, v) {
v += " ";
string += v;
});
});
alert(string);
</script>
see this link also very useful
Loop through JSON object List
I didn't format the string properly , please check that
Assume your json has this format
[ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" }, { "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
Assume you have response in a codes object
var finalHtml='';
finalHtml='<table>
<thead>
<tr>
<th>code</th> <th>lastname</th> <th>firstname</th>
</tr>
</thead>
<tbody>
<tr>'
for(i=0; i< codes.length;i++)
{
//store the values and paint the html
finalHtml+=<td>0codes[i].code;</td> <td>codes[i].lastname </td> <td>JEFFERSON</td>;
}
</tr>
</tbody>
</table>'
append to the dom finally
have some container and do
$('#containerID').html(finalHtml);
i have an table
<table class="oldService">
<thead>
<th>name</th>
<th>age</th>
<th>action</th>
</thead>
<tbody>
<?php foreach($array as $k=>$v){ ?>
<tr>
<td><?php echo $k[name] ?></td>
<td><?php echo $k[age]?></td>
<td id="<?php $k[id]" class="delme">X</td>
</tr>
<?php } ?>
</tbody>
<table>
now i want to delete any row by clicking on X of each row except first and last row,
and also need to confirm before deletion.
i used below jquery
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('table.oldService>tbody tr').not(':first').not(':last').click(function(){
if(confirm('want to delete!')){
jQuery(jQuery(this).addClass('del').fadeTo(400, 0, function() {
jQuery(this).remove()}));
jQuery.get('deleteService.php', {id:jQuery(this).attr('id')});
}
else return false;});
});
</script>
this is working perfect,but it execute by click on that row( means any td), i want that this event only occour when user click on X(third td) .
please suggest me how to modify this jquery so that the event occur on click of X.
UPDATE:
i want that minimum one row should be in tbody,
means if there is only one row then no function to delete that row, and if there is many rows then any row he can delete but not the all rows.
You can do this with a bit less code like this:
jQuery('table.oldService').delegate('td.delme', 'click', function() {
if(jQuery(this).parent().siblings(":not(.del)").length === 0) return;
if(!confirm('want to delete!')) return;
jQuery.get('deleteService.php', { id:this.id });
jQuery(this).parent().addClass('del').fadeTo(400, 0, function() {
jQuery(this).remove();
});
});
This attaches one event handler for the table instead of 1 per <td>. First we check if there are any siblings left that aren't deleted (prevent last deletion). Then check if they confirm, then delete the row.
You also need a few html fixes based on the posted question. The last tag needs to be </table> instead of <table>, and those <td> elements in the <thead> need to be wrapped in <tr></tr>. Let me know if you have any trouble, you can see a working demo of this here.
I didn't implement all your animation and AJAX logic, but here is how you could do this in general:
$(function() {
$('table.oldService td.delme:not(:first):not(:last)').click(function() {
$(this).closest('tr').remove();
});
});
Also, I highly recommend you run your code through JSLint. The code sample you posted has a massive number of errors in it.
Try this :
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('table.oldService>tbody tr img.delete').not(':first').not(':last').click(function () {
if(confirm('want to delete!'))
{
jQuery(jQuery(this).addClass('del').fadeTo(400, 0, function() {
jQuery(this).parent().parent().remove()}));
jQuery.get('deleteService.php', {id:jQuery(this).attr('id')});
}
else return false;});
});
</script>
html :
<table class="oldService">
<thead>
<th>name</th>
<th>age</th>
<th>action</th>
</thead>
<tbody>
<?php foreach($array as $k=>$v){ ?>
<tr>
<td><?php echo $v['name'] ?></td>
<td><?php echo $v['age']?></td>
<td><img id="<?php echo $v['id']?>" class="delete" src="del.gif" /></td>
</tr>
<?php } ?>
</tbody>
<table>