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;
}
},
Related
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);
}
});
});
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 have a button group consisting of two buttons, each assigned an id and a value :
echo "<div style='margin-top:20px;' class='btn-group'>
<button type='button' class='btn btn-primary' id='btnconventional' value='conventional' style=' border-radius: 3px;'>Conventional Units</button>
<button type='button' class='btn btn-primary' id='btnsi' value='si' style=' border-radius: 3px;'>SI Units</button>
</div>";
And then i want to submit a query and table result depending on the value of the button that will be sent via this ajax script :
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing conventional units');
},
error: function(result) {
alert('error');
}
});
});
</script>
Now when i try to get the variable and run my code, nothing appears but the else statement:
if(isset($_POST['Metric']) && !empty($_POST['Metric'])){
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC'";
$result2 = $conn->query($sql2);
echo $_POST['Metric'];
echo "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "<button onclick='hideLabResult();'>Back</button>";
}
else echo "Nope";
The success alert is showing after clicking the button, yet "Nope" still shows after the click, it's not going into the if statement and I can't seem to find out way, I'm a starter in ajax and I'd appreciate any tip or help please.
So in success you are only registered to display information about a successful request, not its contents. To display its contents, use $('.btn-group').html(result); for jquery example.
well, when I run the code on my local , I found ajax was not sending the request to correct page. When I put url then success message was showing there with all html code(whole page I mean). Then I write isset condition on top of page and at ending of } i put exit().
Now its working.
<?php
if(isset($_POST['Metric']) && !empty($_POST['Metric']))
{
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC' ";
$result2 = $conn->query($sql2);
$html = $_POST['Metric'];
$html.= "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
$html.= "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
$html .="<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
$html .= "<button onclick='hideLabResult();'>Back</button>";
echo $html;
} else echo "Nope"; ?>
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
url : '', // put your page url
success: function(result) {
alert('Viewing conventional units'+result);
},
error: function(result) {
alert('error');
}
});
});
</script>
I want to apply conditions on data-column-id which is being fetched from php code.Is this possible to do something like this?
if(data-column-id)==0{
data-column-id="ordinary";
}else{
data-column-id="ordinary";
}// i want this for cat_type
table
<table id="categories_grid" class="table table-condensed table-hover table-striped" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="cat_id" data-type="numeric" data-identifier="true">CatID</th>
<th data-column-id="cat_name">Name</th>
<th data-column-id="cat_type">Type</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
AJAX
$( document ).ready(function() {
var grid = $("#categories_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_categories.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.cat_id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.cat_id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
}
/* "type":function (column,row) {
if(row.cat_type == 0)
{
return "ordinary";
}
else
return "special";
}*/
}
}).on("loaded.rs.jquery.bootgrid", function()
A check like this, and the setting of the data attribute can be done via JavaScript. Here I will be using jQuery.
Given a DOM element:
<th id='test_id' data-column-id="cat_id" data-type="numeric" data-identifier="true">CatID</th>
We can select it, and its data attributes as such. In order to select it more easily and for example purposes I've added an id to the table header above. (test_id)
var column_id = $('#test_id').data('column-id');
Now that we have its value we can perform the check you wish:
if(column_id == 0){
// logic
}else{
// logic
}
In order to set a data attribute you simply do the following:
$('#test_id').data('column-id', 'some value');
Following this statement your DOM element becomes:
<th id='test_id' data-column-id="some value" data-type="numeric" data-identifier="true">CatID</th>
I have data table that populates data from the database, I'm using an Ajax Call to Populate the data on the table and I'm using jQuery RowSorter.js to make my table rows draggable. The my query in my data is sorted by sortorder column. Provided that it is draggable, how can I make the sort permanent in the table and be saved on the database. The sortorder should also be updated depending on what sort order the user choose in the draggable table rows. Here's my code:
Ajax:
$.ajax({
url: "api/question/all",
type: 'GET',
success: function(result){
var myObj = $.parseJSON(result);
$.each(myObj, function(key,value) {
var t = $('#QuestionList').DataTable();
t.row.add( [
value.id,
value.columnheader,
value.costperlead,
// value.isenabled,
"<label class='toggle'><input type='checkbox' checked='' id='"+value.columnheader+"'><span class='handle'></span></label>",
value.sortorder,
"<a class='btn btn-small btn-info' href='<?php echo URL::to('question').'/';?>"+value.id+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>",
"<form method='POST' action='<?php echo URL::to('question').'/';?>"+value.id+"' accept-charset='UTF-8' class='pull-left' >"+
"<input name='_method' type='hidden' value='DELETE'>"+
"<button type='submit' class='btn btn-warning'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>"+"</form>",
] ).draw();
if(value.isenabled == "Yes")
{
$("#"+value.columnheader).prop('checked', true);
}
else if(value.isenabled == "No")
{
$("#"+value.columnheader).prop('checked', false);
}
});
}}).error(function(){
progress.progressTimer('error', {
errorText:'ERROR!',
onFinish:function(){
alert('There was an error processing your information!');
}
});
}).done(function(){
progress.progressTimer('complete');
$( "#progressbar" ).fadeOut( "slow" );
});
My Table HTML
<table id="QuestionList" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th colspan="5"> <center>Question Information<center></th>
<th colspan="2"> <center>Actions<center></th>
</tr>
<tr>
<th>ID</th>
<th>Column Header</th>
<th>Cost Per Lead</th>
<th>Is Enabled?</th>
<th>Sort Order</th>
<th>Edit/View</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7"> </td>
</tr>
</tfoot>
</table>
JS to Call rowsorter
$("#QuestionList").rowSorter({
onDrop: function(tbody, row, index, oldIndex) {
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
}
});
My Query
public function apiGetQuestions()
{
$questions = Question::orderBy('id', 'DESC')->get();
return json_encode($questions);
}
I'm using Laravel 5, any ideas or guides will be appreciated. Thanks!
Update:
Using Jquery's rowsorter function I can keep track of the positions of the rows and its new position:
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
You don't want to store the entire table, but you can store the sorting events. Everytime a user clicks on a column, you add that to a sort sequence array and save the array serialized.
var sortSequence = [];
$('th').click(function() {
// direction: 'asc' or 'desc'
sortSequence[$(this).text()] = get_direction_from_jquery_sort_plugin_somehow();
var data = {
'table': ...,
'sequence': sortSequence.serialize()
};
$.post('store-sequence', data);
});
I would then have some sanitization in place when storing the sorting to remove any duplication or ascending, descending, ascending sequences.
Then when retrieving the data, you add the sorting sequence as orderBy() calls.
$query = \DB::table("my_table")->where(...);
$sorts = $this->fetchSorting(\Auth::user(), "my_table");
foreach ($sorts as $column => $direction) {
$query->orderBy($column, $direction);
}
This is all a lot of work however and I wonder if it is really worth it.