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.
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>
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 a multi-step form that allows the user to save for later or submit. If they save for later, i want them to have an option to edit or delete but if they submit, i dont want them to have any option to edit or delete. Although the following code makes sense, its not working; i'm not getting any buttons and it breaks the jquery table plugin and i dont have the search or pagination option:
<table id="myTable" class="table table-bordered table-hover table-striped tablesorter table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Status</td>
<td>Date/Time</td>
<td>Tag</td>
<td>Serial Number</td>
<td>Equipment</td>
<td>Company</td>
<td>Grand Total</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['id']."</td>";
echo "<td><span class='label ".$res['labelwarning']."'>".$res['status']."</span></td>";
echo "<td>".$res['todaysdatetime']."</td>";
echo "<td>".$res['tag']."</td>";
echo "<td>".$res['serialnumber']."</td>";
echo "<td>".$res['currentequipment']."</td>";
echo "<td>".$res['company']."</td>";
echo "<td>".$res['total_grandtotal']."</td>";
$Submitted = "Submitted";
$Saved = "Saved";
if ($res['labelwarning'] == $Submitted) {
echo "<td></td>";
} elseif ($res['labelwarning'] == $Saved) {
echo "<td></td>";
}
echo "</tr>";
}
?>
<Script>
$(document).ready(function() {
$("#myTable").dataTable({
"aaSorting": [ [0,'desc'] ]
});
});
</Script>
Oke I will try to explain this process here:
1 - First you will create a php file where you will fetch the results you need.
when you are fetching the records you will put your results in a variable like so:
$result_html = '';
while($res = mysqli_fetch_array($result)) {
$result_html .= "<tr>";
$result_html .= "<td>".$res['id']."</td>";
...en so on
$result_html .= "</tr>";
}
To return the response to your ajax call you need to add also this:
echo json_encode($result_html);
2 - Before the end </body> tag
<script>
$(document).ready(function() {
$.ajax({
url: '/path/to/the_php_file',
type: 'POST',
dataType: 'json',
data : { //only needed if you have to pass parameters to your query },
})
.done(function(data) {
//data is your html response
// and #returnedResponse is the id given to your body tag
$('#returnedResponse').html(data);
$("#myTable").dataTable();
})
.fail(function() {
console.log("error");
});
});
</script>
3 - Your table
<table id="myTable" class="table table-bordered table-hover table-striped tablesorter table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Status</td>
<td>Date/Time</td>
<td>Tag</td>
<td>Serial Number</td>
<td>Equipment</td>
<td>Company</td>
<td>Grand Total</td>
<td>Action</td>
</tr>
</thead>
<tbody id="returnedResponse">
</tbody>
</table>
NOTE:
You need to have the link to the jquery.js before your ajax call.
This is not a copy and paste solution. You asked for an example on how to do it and here you have a good start point to learn it.
Try to change your if/else part to this:
if ($res['labelwarning'] == $Submitted) {
echo "<td></td>";
} else{
echo "<td></td>";
}