I'm trying to get table data to my view table using Codeigniter and AJAX jQuery.
Well, I'm using a document ready function to get the data instead of passing the table data when calling the view on the controller.
Ajax function
$( document ).ready(function() {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
alert("sucesso - " + data);
$('#example1').html(data);
},
error: function() {
alert('Algo falhou, nao caregou a tabela. - ' + data);
}
});
});
Controller method
public function crud_getDataAll($table_name)
{
$data = $this->Administracao_model->getAllData($table_name);
echo json_encode($data);
}
Model method
function getAllData($table_name)
{
$this->db->select('*');
$query = $this->db->get($table_name);
return $query->result();
}
View table
<table id="example1" class="table table-sm table-bordered table-striped Responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if($data){ foreach($data as $row) { ?>
<tr>
<td class="align-middle text-center">
<?php echo $row->id;?>
</td>
<td class="align-middle text-center">
<span class="badge <?php echo $row->classes; ?>">
<?php echo $row->none;?>
</span>
</td>
<?php $ad = $row->adicionar; $el = $row->eliminar; $al = $row->alterar; $pe = $row->pesquisar; ?>
<td>
<?php echo $ad .", ". $el . ", ". $al . ", " . $pe; ?>
</td>
</tr>
<?php } } ?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
Is there something that I'm doing wrong? Thanks in advance.
Php error:
Severity: Notice
Message: Undefined variable: data
EDITED
output of echo json_encode($data);
[
{
"id": "1",
"nome": "Nivel 0",
"classe": "badge-admin-0",
"adicionar": "1",
"remover": "1",
"alterar": "1",
"pesquisar": "1"
},
{
"id": "2",
"nome": "Teste",
"classe": "badge-danger",
"adicionar": "1",
"remover": "0",
"alterar": "0",
"pesquisar": "0"
}
]
Basically you have 2 options here. First of all, if you're not passing $data to your HTML table, then remove PHP codes:
<table id="example1" class="table table-sm table-bordered table-striped table-responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
but if you're passing the data, leave as it is.
Option 1: Output data as HTML
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'html',
success: function(data) {
$('#example1 tbody').html(data);
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});
Then, in your controller, output data as HTML:
public function crud_getDataAll($table_name)
{
$rows = $this->Administracao_model->getAllData($table_name);
foreach($rows as $row) {
echo '<tr>';
echo '<td class="align-middle text-center">' . $row->id . '</td>';
echo '<td class="align-middle text-center"><span class="badge ' . $row->classe . '">' . $row->nome . '</span></td>';
echo '<td>' . $row->adicionar . ', ' . $row->eliminar . ', ' . $row->alterar . ', ' . $row->pesquisar . '</td>';
echo '</tr>';
}
}
Option 2: Output data as JSON
Just update your AJAX callback:
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'json',
success: function(rows) {
if (rows) {
rows.forEach(function(row) {
$('#example1 tbody').append(`<tr><td class="align-middle text-center">${row.id}</td><td class="align-middle text-center"><span class="badge ${row.classe}">${row.nome}</td><td>${row.adicionar}, ${row.eliminar}, ${row.alterar}, ${row.pesquisar}</td></tr>`);
});
}
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});
Related
I am new in AJAX and API`s:
I have created API (that returns an array of Status Items)
1- Index.php have the below code for the datatable:
<table id="example1" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th class="center">Edit</th>
<th class="center">Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot class="table-condensed table-bordered">
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
The second file2.php includes the Javascript and Jquery and Ajax code:
I write the code below to get the Json from the api and fetch the rows into the above table:
var table = $("#example1 tbody");
$.ajax({
url: 'API_ReadAllSeed_Status.php',
method: "GET",
xhrFields: {
withCredentials: true
},
success: function (data) {
table.empty();
$.each(data.AllStatus, function () {
var Active_Status = "";
//the code below is to set a specific element depending on the result
if (this["STATUS_ACTIVE"] == 1)
{Active_Status = "<td><span class='label label-success'>Activated</span></td>";}
else
{Active_Status = "<td><span class='label label-danger'>Deactivated</span></td>"}
table.append("<tr><td>" + this["STATUS_CODE"] + "</td><td>" + this["STATUS_DESCRIPTION"] + "</td>" + Active_Status + "</td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='fa fa-edit'></i> Edit </a></td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='glyphicon glyphicon-trash'> </i> Delete</a></td> </tr>");
});
}
});
Result:
The Json fetch successfully as I want but as shown in the picture, the rows are not inserted in the main body rows of the data table since nothing is working inside.
My Question:
How I am able to load the Json data into the datatable and use all its features [search and pagination and rows per page].
Finally it works nowt but still have a question:
$('#STATUS_TABLE').DataTable({
"ajax": {
"url": "API_ReadAllSeed_Status.php",
"dataSrc": "AllStatus"
},
"columns": [
{ "data": "STATUS_CODE" },
{ "data": "STATUS_DESCRIPTION" },
{ "data": "STATUS_ALT_DESCRIPTION" },
{ "data": "STATUS_ACTIVE" }
]
});
Question:
How I can change the format of the rows and to set different labels of the Status example rows with value 1 = Active and 0 = Deactivate.
After many searches and after trying many codes I found the below solution:
{ "data" : "STATUS_ACTIVE",
render : function(data, type, row) {
if (data == 1)
{data = "<span class='label label-success'>Activated</span>";}
else
{data = "<span class='label label-danger'>Deactivated</span>";}
return data;
}
},
I want to pass the value from jquery to php using AJAX, the problem is the value in the php is not properly set.
Here is my sample codes:
Button trigger to pass data into jquery.
<button class="btn btn-info add-percentage"
data-landing_id-percentage="'.$row['hidden_id'] .'"
data-toggle="add-percentage"><i class="glyphicon glyphicon-time"></i></button>
Below is the ajax and jquery code.
<script>
$(".add-percentage").click(function(){
var landing_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
data: {
landing_id: landing_id
},
success: function(msg) {
alert('Email Sent'+msg);
$('#add-percentage').modal('show');
readRecords();
}
});
});
<script>
The result below in the php code is the landing_id is not properly set.
readPercentage.php
<?php
$data = '
<table class="table table-bordered table-hover table-striped" id="ModalMyTable">
<thead>
<tr class="success">
<th ><center>No.</center></th>
<th ><center>Percentage ID</center></th>
<th ><center>Landing ID</center></th>
<th><center>Percentage</center></th>
<th><center>Date Added</center></th>
</tr>
</thead>';
if(isset($_POST['landing_id'])){
$landing_id = $_POST['landing_id'];
$query = mysqli_query($conn, "SELECT
percentage.percent_id,
percentage.landing_id,
percentage.percentage,
percentage.date_recorded
FROM
percentage
WHERE percentage.landing_id = '$landing_id'");
$number = 1;
while($row = mysqli_fetch_assoc($query)) {
$data .= '
<tr>
<td><center>' . $number . '</center></td>
<td><center>' . $row['percent_id'] . '</center></td>
<td><center>' . $row['landing_id'] . '</center></td>
<td><center>' . $row['percentage'] . '%</center></td>
<td><center>' . date("M. d, Y", strtotime($row['date_recorded'])) . '</center></td>
</tr>';
$number++;
}
}else{
$data .='<tr><td colspan="6">Landing id is not properly set!</td></tr>';
}
$data .= '</table>
<script>
{
$(document).ready(function(){
$("#ModalMyTable").DataTable();
readRecords();
});
}
</script>
';
echo $data;
?>
I hope some one can help me in my problem. Thanks in advance.
I am using CodeIgniter, I have a form and fields are Employee_name, fromDate, and endDate. I am sending the data to Ajax.(I haven't shared the form code and model code) Now I am displaying the records from database using AJAX and JSON. I am getting the correct output from the database but there is some issue I don't know it's JSON or another issue. I am getting the undefined and then getting my output.
In below image, I am getting the total 9 records from the database which is correct but when I am displaying using JSON then I am getting 18 records. First 9 records undefined and next 9 records my output.
Would you help me out in this issue?
View
<!--form code here-->
<form name="employee_attendance"></form>
<!--end form code here-->
$("form[name='employee_attendance']").validate({
rules: {
employee_Name: {
required: true
},
fromDate: {
required: true
},
toDate: {
required: true
}
},
submitHandler: function(form) {
var employee_Name = $('#employee_Name').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: baseUrl + "/Reports_control/report_attendance",
method: "POST",
//dataType: "json",
data: {
employee_Name: employee_Name,
fromDate: fromDate,
toDate: toDate
},
success: function(response) {
$('.search_record tbody tr').hide();
var data = JSON.parse(response);
if (data.status === 'error') {
alert(data.msg);
}
if (data.status === 'success') {
$('.addendence_report_list').show();
var trHTML = '';
$.each(data.records, function(i, o) {
trHTML += '<tr><td>' + o.Sr_no +
'</td><td>' + o.name +
'</td><td>' + o.employee_id +
'</td><td>' + o.last_activity +
'</td><td>' + o.total_days +
'</td></tr>';
});
$('.search_record tbody').append(trHTML);
}
}
});
}
});
Controller
public function report_attendance()
{
$employee_id=trim($this->input->post('employee_Name'));
$fromDate=trim(date('Y-m-d', strtotime($this->input->post('fromDate'))));
$toDate=trim(date('Y-m-d', strtotime($this->input->post('toDate'))));
if((!empty($employee_id)) && (!empty($fromDate)) && (!empty($toDate))){
$result=$this->Reports_model->get_employee_attendance($employee_id,$fromDate,$toDate);
}
if (empty($result) || $result == 0){
$arr_result['status'] = "error";
$arr_result['msg'] = "No record found";
}
else
{
$n=1;
foreach ($result as $row)
{
$result[] = array(
"Sr_no" => $n,
"name" => $row->firstname.' '.$row->lastname,
"employee_id" => $row->employee_id,
"last_activity"=>$row->login_time,
"total_days"=>$row->total_days
);
$n++;
}
$arr_result['status'] = 'success';
$arr_result['records'] = $result;
}
echo json_encode($arr_result);
exit;
}
view
<div class="search_record">
<table cellspacing="0" id="attendence_report_list">
<thead>
<tr>
<th class="" width="5%">Sr. No.</th>
<th class="" width="11%">Name</th>
<th class="" width="11%">Emp Id</th>
<th class="" width="9%">Date </th>
<th class="" width="9%">Working hours</th>
<th class="" width="9%">Leave Days</th>
</tr>
</thead>
<tbody>
<tr>
<tr>
</tr>
</tbody>
</table>
</div>
Change the name of the array in foreach from $result[] to results[] and check it.
I need to set class on table on spesific tr on ajax proses. my html table like below
<table class="table table-striped table-borderless table-hover" id="tablePray">
<thead>
<tr>
<th style="width:20%;">Nama / Name</th>
<th style="width:45%;">Keterangan / Description</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
foreach ($prays as $row)
{
?>
<tr id="prayRow<?php echo $row->id;?> ">
<td class="user-avatar"> <img src="<?php echo base_url();?>assets/admin/img/avatar.gif" alt="Avatar"><?php echo $row->name;?></td>
<td><?php echo $row->prayNeed;?></td>
<td class="text-right"> Healed</td>
</tr>
<?php
}
?>
and my jquery like this :
$('#changeStatusFrm').submit(function(e) {
e.preventDefault();
$id=$('#idPray').val();
$token=$('#token').val();
data = new FormData();
data.append("idPray",$id);
data.append("<?php echo $this->security->get_csrf_token_name();?>", $token );
$.ajax({
data: data,
type: "POST",
url: '<?php
echo base_url('Pray/ChangeStatus');
?>'
,
cache: false,
contentType: false,
processData: false,
success: function(url) {
var result=url.split('|');
$('#token').val(result[0]);
alert('Pray status have been change');
$("#mod-danger").modal("hide");
$("#tablePray tr#prayRow"+$id).addClass('table-success');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I want to change the spesific tr if row link get click.
Can anybody help me?? thx
If you are using datatable then you can use something like this :
$('#tablePray').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 0 ] }
]
} );
reference link :- https://datatables.net/reference/option/columns.className
This example here demonstrates adding and removing classes on a row from a click event.
Set like this
var val = "#prayRow"+$id;
$(val).addClass('table-success');
Make sure #prayRow$id is already defined in table
FYI: move alert('Pray status have been change'); to end of the line
I need a solution for this. Here is what I am trying to do. I have a datatable that has some values and check boxes in the first columns. What I need is when I select the check box in the header it should select all the values in the current page only. But all the check boxes of all the pages get selected.
I also want that, When I navigate to another page of the datatable, the check box selections of all the previous page should be unchecked including the check box in the header.
Hear is my code:
<?php if($acl->can('view_article')){ ?>
<table id="articles" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
<tbody>
<?php
foreach($articles as $article) {
$id = $article["id"];
$uid = $article["uid"];
$article_name = $article["article_name"];
$article_file_path = $article["article_file_path"];
$article_category = $article["article_category"];
$article_demographic = $article["article_demographic"];
$article_word_count = $article["article_word_count"];
$intended_month = $article["intended_month"];
$article_created = $article["article_created"];
if(!empty($article_demographic)) {
$article_demographic = implode(", ",$article_demographic);
}
$article_keywords = $article["article_keywords"];
$article_description = $article["article_description"];
$checkbox = in_array($id, $assigned_articles)? " ":"<input type='checkbox' value=".$id." />";
echo "
<tr class='' data-id='$id'>
" ;
if($acl->can('delete_article'))
echo "<td>$checkbox</td>";
if($acl->can('edit_article')){
echo "<td>" . anchor("articles/edit/$id",$article_name.'- '.$article_word_count,"class='notBtn' title=\"$article_description\"") . " </td>";
}else{
echo "<td>$article_name - $article_word_count</td>";
}
echo "
<td>".short_string($article_category)."</td>
<td>".short_string($article_demographic)."</td>
<td> $intended_month </td>
<td align='right'>$article_word_count</td>
</tr>";
}
?>
</tbody>
</table>
<?php } ?>
<script type="application/javascript">
$(document).on( 'init', function ( e, settings ) {
alert( 'Saved page length is: '+ table.state().length );
} );
$(document).ready(function(){
var oTable = $("#articles").DataTable({
"stateSave": true,
"order": [],
"dom": '<"row" <"col-md-12 space" <"datatable-action pull-left"> <"datatable-n pull-right" l > > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
<?php if($acl->can('delete_article')){ ?>
{orderable: false, searchable: false},
<?php } ?>
{"width": "25%" },
null,
null,
{"width": "12%" },
{"width": "10%" },
],
"fnDrawCallback": function( oSettings ) {
$('.popupArticle').viewArticle({
url : '<?=site_url("articles/showArticleInPopup");?>',
title : 'Article Preview',
size : 'lg'
});
}
});
$('#search-inp').on('keyup',function(){
oTable.search($(this).val()).draw() ;
})
if(oTable.state().length != 0)
$('#search-inp').val(oTable.state().search.search);
checkAllCheckbox(oTable);
var deletebtn = '';
<?php if($acl->can('delete_article')){ ?>
var deletebtn = '<i class="fa fa-trash-o"></i>';
<?php } ?>
var assignbtn = '';
<?php if($acl->can('assign_article')){ ?>
var assignbtn = '<i class="fa fa-paperclip"></i>';
<?php } ?>
$("div.datatable-action").html(deletebtn + ' ' +assignbtn);
$('#assignbtn').on('click', function (e) {
e.preventDefault();
eModal.setEModalOptions({loadingHtml : ''});
eModal.iframe('<?= site_url("assignArticles/e/"); ?>', 'Assign Article').then(function (input) {
$('.modal-dialog', window.document).css('width', '80%');
if ($('.modal-footer', window.document).length == 0) {
$('.modal-content', window.document).append('<div class="modal-footer"> </div>');
}
});
});
});
</script>
Here is the code for checkAllCheckbox(oTable);
function checkAllCheckbox(oTable) {
/* Check all in Datatable*/
if ($("#select_all_existent").length != 0) {
var cells = oTable.cells().nodes();
$("#select_all_existent").change(function () {
$(cells).find(":checkbox").prop("checked", $(this).is(":checked"));
});
$(cells).find(":checkbox").change(function(){
if(!$(this).is(":checked")){
$("#select_all_existent").prop("checked", $(this).is(":checked"));
}
else{
if ($(cells).find(":checkbox").length == $(cells).find(":checked").length) {
$("#select_all_existent").prop("checked",true);
}
}
if ($(cells).find(":checked").length > 0) {
$(oTable.table().container()).siblings().find('.help- block').html('');
}
else{
$(oTable.table().container()).siblings().find('.help- block').html('Please select at least one checkbox');
}
});
}
}
Any help on the scenarios that I have mentioned would be appreciated.
In your code made the following changes and try:
change 1: disable sorting of checkbox column
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th data-orderable="false"><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
change 2:
add the following code to script:
$('#articles').on('page.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#articles').on('length.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#select_all_existent').on('change',function () {
checkAllCheckbox(oTable);
});