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>
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 have a table with differente IDs on each row (obtained from a while loop), and next to each ID i have element to view the details of this specific record. Now i understand if i want to retrieve the id, i have to send via post method in a form, but i don't want the page to refresh because i'm using bootstrap tabs, i don't want the page to go back to the first tab, therefore, i'm trying to use Ajax not to make the page refresh.
So first of all i have my first table :
I am in Medical Records Tab > Member Medical Records.
and my View item is :
<td style='text-align:center;'> <ul class='nav nav-tabs'><form><a data-toggle='tab' id='testz' value='".$rowmed[0]."' href='#viewMed' role='button'></form><i style='color: gray;' class='fa fa-eye'></i></a></td></ul>
Now i write an ajax script with the variable recdetailsid in DATA:
<script>
$("#testz").click(function(e) {
switchVisible();
e.preventDefault();
$(this).toggleClass( "selected" );
$.ajax({
type: "POST",
data: {
recdetailsid: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing Details !');
},
error: function(result) {
alert('error');
}
});
});
`
and then to get this ajax element :
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
if(isset($_POST['recdetailsid'])){
$recdetailsid=$_POST['recdetailsid'];
$sqlmedr = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Created 2 same queries with different names because can't fetch_array twice on the same query and need to pull data twice, 1 outside the while and 1 in a while for table results
$sqlmedrx = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Record_id need to be sent on view click !!!!!!!!!!!! now it is specified explicitely
$resultmedr = $conn->query($sqlmedr);
$resultmedrx = $conn->query($sqlmedrx);
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important;">
<h3 style="color:black;">Member Record</h3></div>
<?php
$rowmedrx = mysqli_fetch_array($resultmedrx);
if ($type=='teachers') {
echo "Record Id: <td>".$rowmedrx['Record_id']."</td> ";
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "Notes : <td>".$rowmedrx['Notes']."</td> ";
} else {
$sqlmedr = "Select DISTINCT Record_id,Medical_Condition,Date FROM medicalrecords,teachers,dependants WHERE medicalrecords.Dependant_id=".$comid." and medicalrecords.Dependant_id=dependants.Dependant_id ";
$resultmedr = $conn->query($sqlmedr);
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
}
} }
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important; ">
<h3 style="color:black;">Documents</h3></div>
But everything in the server $_POST brackets and isset $_POST brackets does not show, only the alert shows with the Document jumbotron.
( you can see i'm using the variable inside the query, Record_id=".$recdetailsid." ) , this is my whole purpose !
Can anyone give me some tips or help please ? i'm new to ajax but trying my best to get through this, appreciated!
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>
This is my following code in front End:
<div class="panel panel-primary">
<div class="panel-heading text-center text-uppercase">Birth Certificates For Overall (Pending, Completed)</div>
<div class="panel-body">
<div class="box-body">
<table id="viewer" class="table table-bordered">
<thead>
<tr>
<th>Sr No</th>
<th>Reg Number</th>
<th>From Hospital</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php $Viewer->showAllData(); ?>
</tbody>
<tfoot>
<tr>
<th>Sr No</th>
<th>Reg Number</th>
<th>From Hospital</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
This is my classes code in it of which i have called the object:
public function showAllData()
{
$query = "SELECT * FROM certificate_details ORDER BY created DESC";
$connection = $this->establish_connection();
$details = $connection->query($query);
$connection->close();
if($details->num_rows > 0)
{
$counter = 1;
while($detail = $details->fetch_assoc())
{
$status = $detail['status'];
if($status == 0)
{
$bg = "bg-danger";
$issuestatus = "btn btn-success";
$message = "Confirm Issue!";
}
elseif($status == 1)
{
$bg = "bg-success";
$issuestatus = "btn btn-success disabled";
$message = "Certificate Issued";
}
else
{
$bg = "bg-warning";
$issuestatus = "btn btn-warning";
}
echo "
<tr class='odd gradeX ".$bg."'>
<td>".$counter."</td>
<td>".$detail['registration_number']."</td>
<td>".$this->getHospitalInfo($detail['user_id'])."</td>
<td style='margin: 0;'><div class='btn btn-primary' href='#' value='".$detail['id']."' id='view-details'>View Details</div><div style='margin-left: 10px;' class='".$issuestatus."' href='#' value='".$detail['id']."' id='confirm-issue'>".$message."</div></td>
</tr>
";
$counter = $counter + 1;
}
}
}
I have give a specific id to the button i.e id="view-details" and in the value section it hold the unique value
This is the following JQuery Code which i am triggering whenever i am calling the ("#view-details").click(function(){})
$("#view-details").click(function()
{
var certificateId = $("#view-details").attr('value');
$.ajax({
url: 'get_data.php?id=getCertificateDetails',
type: 'POST',
dataType: 'html',
data: {certificate_id : certificateId},
})
.done(function(resp)
{
var data = $.parseJSON(resp);
if(data.status == 1)
{
var message = "Certificate is Already Issued";
var btn_status = "btn btn-success disabled";
}
else if(data.status == 0)
{
var message = "Click To Confirm Issue!";
var btn_status = "btn btn-danger";
}
else
{
var message = "Technical Issue";
var btn_status = "btn btn-danger disabled";
}
var data = "<div class='modal-dialog'>"+
"<div class='modal-content'>"+
"<div class='modal-header' align='center'>"+
"<h3 class='modal-title'>Certificate Details Are As Follows</h3>"+
"</div>"+
"<div class='modal-body'>"+
"<b>Registration Number</b> : "+data.reg_number+
"<br /><b>Baby's Birth Date</b> : "+data.birth_date+
"<br /><b>Baby's Birth Time</b> : "+data.birth_time+
"<br /><b>Baby's Gender</b> : "+data.gender+
"<br /><b>Baby's Full Name</b> : "+data.baby_name+
"<br /><b>Father's Full Name</b> : "+data.fathers_name+
"<br /><b>Mother's Full Name</b> : "+data.mothers_name+
"<br /><b>Parent's Address While Baby's Birth</b> : "+data.while_baby_birth_parents_address+
"<br /><b>Parent's Permanent Address</b> : "+data.parents_permanent_address+
"<hr /><h4 class='text-center'>Hospital Details</h4>"+
data.hospital_detail+
"<hr /><h4 class='text-center'>Home Details</h4>"+
data.home_detail+
"<hr /><h4 class='text-center'>Other Details</h4>"+
data.other_detail+
"</div>"+
"<div class='modal-footer'>"+
"<button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>"+
"<a href='#' class='"+btn_status+"' id='confirm-issue'>"+message+"</a>"+
"</div>"+
"</div>"+
"</div>";
$('#viewDetails').html(data);
$('#viewDetails').modal('show');
})
.fail(function()
{
console.log("error");
});
});
The problem arises when lets take a scenario
have a look at this screenshot
when i click on view details of the very first record the modal is called, but when i click on the next view details the modal doesn't appear. it seems that the modal appears only for the very 1st record present in the table
please can anyone help me with this code
you are generating multiple elements with the same id ("view-details"). That's invalid HTML. Element IDs must be unique. Your click event handler will only work on the first one because it considers that all the later ones are not valid.
Use classes instead (e.g. $( "body" ).on( "click", ".view-details"... instead of $("#view-details").click(... and <div class='btn btn-primary view-details'... as the button (instead of id="view-details")
#view-details id always unique so your modal will only work with first where ever it comes.
For more details about Difference between id and class in CSS and when to use it
so you need to add a class to open model, and some change in your code
HTML :
id='view-details' to <div class='btn btn-primary view-details'>
JS:
$( "body" ).on( "click", ".view-details", function() {
var certificateId = $( this ).attr('value');
// .... Rest of your code here
});
Why Use jQuery .on() because it will bind click handler to every button holding view-details class.
var certificateId = $( this ).attr('value');
Will give you current clicked button's attribute value.
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.