HighCharts data defined in a HTML Table using PHP MySQL - php

I'm using HighCharts to display a chart that is pulling data on HTML Table and my table is populated by PHP. Somehow it displaying the Title of the Chart which is Announcement Likes Chart but the Bar Chart is not included in it. Any answer with or without explanation is highly appreciated :)
<table class="table table-striped table-hover ">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="tables">Announcement Table</h1>
</div>
<div id="tablecon" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<table id="datatable" class="table table-striped table-hover ">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Likes</th>
</tr>
</thead>
<tbody class="table table-bordered table-hover ">
<?php
//set up mysql connection
mysql_connect("localhost", "brmhelpd_root", "siopao04") or die(mysql_error());
//select database
mysql_select_db("brmhelpd_brm") or die(mysql_error());
//select all records form tblmember table
$query = 'SELECT type,title,likes FROM newsfeed ORDER BY created_at ASC';
//execute the query using mysql_query
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
//then using while loop, it will display all the records inside the table
while ($row = mysql_fetch_array($result)) {
echo ' <tr> ';
echo ' <td> ';
echo $row['type'];
echo ' </td> ';
echo ' <td> ';
echo $row['title'];
echo ' </td> ';
echo ' <td> ';
echo $row['likes'];
echo ' </td> ';
echo ' </tr> ';
}
?>
</tbody>
</table>
</div>
</div>
</table>
</div>
</div>
</div>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="login-folder/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="login-folder/assets/js/custom.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="js/jquery.dataTables.min.js"></script>
<script src="js/dataTables.bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#datatable').DataTable( {
"lengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]]
});
} );
</script>
<script>
$(function () {
$('#tablecon').highcharts({
data: {
table: 'datatable'
},
chart: {
type: 'column'
},
title: {
text: 'Announcement Likes Chart'
},
yAxis: {
allowDecimals: true,
title: {
text: 'Units'
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.point.y + ' ' + this.point.name.toLowerCase();
}
}
});
});
</script>

I'm giving up to this problem. I'll populate my table with ajax better thanks for Sebastian Bochan suggestion.

Related

Dynamic Drag and Drop table rows

I try to make some reorder with drag and drop with PHP and some ajax with this tutorial.
I set up my files for my needs but nothing going on.
On my index.php just change this thing that equal to my MySQL
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
Here is Java script in index.php:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
var selectedData = new Array();
$('.row_position>tr').each(function() {
selectedData.push($(this).attr("id"));
});
updateOrder(selectedData);
}
});
function updateOrder(data) {
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:data},
success:function(){
alert('your change successfully saved');
}
})
}
</script>
</html>
Here is and ajaxPro.php that i change:
require('db_config.php');
$position = $_POST['position'];
$i=1;
foreach($position as $k=>$v){
$sql = "Update `channels` SET `channel_number`=".$i." WHERE `id`=".$v;
$mysqli->query($sql);
$i++;
}
And here is MySQL
When I try to reorder, just want to change field channel_number but nothing goings-on. Where is my mistake
I've change some code, and turn on some log, but still have problem. If anyone can assist will be so happy. Here it is:
index.php
<div class="container">
<h3 class="text-center">Dynamic Drag and Drop table rows in PHP Mysql - ItSolutionStuff.com</h3>
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">#</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody class="row_position">
<?php
require('db_config.php');
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>"> <!-- data-channel-number="<?php echo $user['channel_number'] ?>">-->
<td><?php echo $user['id'] ?></td>
<td class="index"><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- container / end -->
</body>
<!--<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
//console.log(chArray);
}
});
</script>-->
<script>
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function(e, ui) {
$('td.index', ui.item.parent()).each(function (i) {
$(this).text(i+1);
});
};
$("#myTable tbody").sortable({
distance: 5,
//delay: 100,
opacity: 0.6,
cursor: 'move',
helper: fixHelperModified,
update: function() {
var chArray = [];
$('.row_position>tr').each(function() {
chArray.push({
chid : $(this).attr("id"),
chnumber : $(this).closest('tr').find('td.index').text()
});
});
console.log(chArray);
// console.log(data);
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:chArray},
success:function(data){
console.log(data);
//alert('your change successfully saved');
},
error: function (error) {
// console.log(error);
}
})
},
stop: updateIndex
}).disableSelection();
</script>
</html>
ajaxPro.php
error_reporting(1);
require('db_config.php');
$data = $_POST['position'];
echo $data;
//$i=1;
foreach($data as $d){
echo $d['chnumber'];
$sql = "Update channels SET channel_number=".$d['chnumber']." WHERE id=".$d['chid'];
$mysqli->query($sql);
}
It's look good in browser everything is changed (if i move chanel from possition 4 to position 2 it's change on the screen to position 2, but in array chnumber is still 4, and i don't know how to change this.
Here is some pics.
1st order when you load page
Reorder when move channel from pos:4 to pos:2
And here is console log

can't transfer php ajax to mysql amchart chart

php ajax and mssql amchart graphic design I'm using. I only want to get out of the graphics when I do the graphics when the page is opened only when I open it, but loading data is coming where the chart is located
I'm pulling my data from range.php
amchart does not come to my garage alone, I am using ajax method
please help me as my code below
index.php page
<?php
$conn = odbc_connect("Driver={SQL Server Native Client 11.0};Server=DESKTOP-G2FDO11;Database=Mapa;Trusted_Connection=Yes", "", "");
$query = "SELECT TOP (1000) [id]
,[firin_adi]
,[Akim]
,[voltaj]
,[Guc]
,[zaman]
FROM [Mapa].[dbo].[test]";
$sql = odbc_exec($conn, $query);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Date Range Search with jQuery DatePicker using Ajax, PHP & MySQL | softAOX Tutorial</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
</head>
<body>
<br/>
<div class="container">
<h2 align="center">Date Range Search with jQuery DatePicker using Ajax, PHP & MySQL</h2>
<br/>
<br/>
<div class="col-md-2">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-2">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-8">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
<div class="clearfix"></div>
<br/>
<div id="purchase_order">
<table class="table table-bordered">
<tr>
<th width="10%">id</th>
<th width="35%">firin_adi</th>
<th width="40%">Akim</th>
<th width="10%">Voltaj</th>
<th width="5%">zaman</th>
</tr>
<?php
while($row= odbc_fetch_array($sql))
{
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["firin_adi"]; ?></td>
<td><?php echo $row["Akim"]; ?></td>
<td><?php echo $row["voltaj"]; ?></td>
<td>$ <?php echo $row["zaman"]; ?></td>
</tr>
<?php
}
?>
<tr>
<!-- Styles -->
<style>
#chartdiv {
width : 100%;
height : 500px;
}
</style>
<!-- Resources -->
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
<script src="https://www.amcharts.com/lib/3/themes/none.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>
<!-- Chart code -->
<script>
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"titles":[{"text":"Step Line Chart"}],
"theme": "none",
"autoMarginOffset":0,
"dataLoader": {
"url": "http://localhost/filter/range.php"
},
"valueAxes": [{
"axisAlpha": 0,
"position": "right"
}],
"graphs": [{
"id":"g1",
"balloonText": "[[zaman]]<br><b>[[Akim]] C</b>",
"type": "step",
"lineThickness": 2,
"bullet":"square",
"bulletAlpha":0,
"bulletSize":4,
"bulletBorderAlpha":0,
"valueField": "Akim"
}],
"chartScrollbar": {
"graph":"g1",
"gridAlpha":0,
"color":"#882525",
"scrollbarHeight":100,
"backgroundAlpha":0,
"selectedBackgroundAlpha":0.1,
"selectedBackgroundColor":"#888888",
"graphFillAlpha":0,
"autoGridCount":true,
"selectedGraphFillAlpha":0,
"graphLineAlpha":1,
"graphLineColor":"#c2c253",
"selectedGraphLineColor":"#888888",
"selectedGraphLineAlpha":1
},
"chartCursor": {
"fullWidth":true,
"categoryBalloonDateFormat": "JJ:NN:SS, DD MMMM",
"cursorAlpha": 0.01,
"graphBulletAlpha": 10
},
"categoryField": "zaman",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
},
"export": {
"enabled": true,
"dateFormat": "YYYY-MM-DD HH:NN:SS"
}
});
chart.addListener("dataUpdated", zoomChart);
function zoomChart(){
chart.zoomToDates(new Date(2018, 0), new Date(2020, 0));
}
</script>
<!-- HTML -->
<div id="chartdiv"></div>
</tr>
<?php
?>
</table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<!-- Script -->
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function(){
var From = $('#From').val();
var to = $('#to').val();
if(From != '' && to != '')
{
$.ajax({
url:"range.php",
method:"POST",
data:{From:From, to:to},
success:function(data)
{
$('#purchase_order').html(data);
}
});
}
else
{
alert("Please Select the Date");
}
});
});
</script>
</body>
</html>
//////////////
range.php page
<!doctype html>
<html>
<head><script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script></head>
<?php
// Range.php
if(isset($_POST["From"], $_POST["to"]))
{
$conn = odbc_connect("Driver={SQL Server Native Client 11.0};Server=DESKTOP-G2FDO11;Database=Mapa;Trusted_Connection=Yes", "", "");
$result = '';
$query = "SELECT TOP (1000) [id]
,[firin_adi]
,[Akim]
,[voltaj]
,[Guc]
,[zaman]
FROM [Mapa].[dbo].[test] WHERE [zaman] BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."'";
$sql = odbc_exec($conn, $query);
$result .='
<table class="table table-bordered">
<tr>
<th width="10%">id</th>
<th width="35%">Cfirin_adi</th>
<th width="40%">Akim/th>
<th width="10%">guc</th>
<th width="5%">zaman</th>
</tr>
';
if(odbc_num_rows($sql) > 0)
{
while($row = odbc_fetch_array($sql))
{
$result .='
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["firin_adi"].'</td>
<td>'.$row["Akim"].'</td>
<td>'.$row["voltaj"].'</td>
<td>'.$row["zaman"].'</td>
</tr>';
}
$result .='<tr>
<!-- Styles -->
<style>
#chartdiv {
width : 100%;
height : 500px;
}
</style>
<!-- Resources -->
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
<script src="https://www.amcharts.com/lib/3/themes/none.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>
<!-- Chart code -->
<script>
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"titles":[{"text":"Step Line Chart"}],
"theme": "none",
"autoMarginOffset":0,
"dataLoader": {
"url": "http://localhost/filter/range.php"
},
"valueAxes": [{
"axisAlpha": 0,
"position": "right"
}],
"graphs": [{
"id":"g1",
"balloonText": "[[zaman]]<br><b>[[Akim]] C</b>",
"type": "step",
"lineThickness": 2,
"bullet":"square",
"bulletAlpha":0,
"bulletSize":4,
"bulletBorderAlpha":0,
"valueField": "Akim"
}],
"chartScrollbar": {
"graph":"g1",
"gridAlpha":0,
"color":"#882525",
"scrollbarHeight":100,
"backgroundAlpha":0,
"selectedBackgroundAlpha":0.1,
"selectedBackgroundColor":"#888888",
"graphFillAlpha":0,
"autoGridCount":true,
"selectedGraphFillAlpha":0,
"graphLineAlpha":1,
"graphLineColor":"#c2c253",
"selectedGraphLineColor":"#888888",
"selectedGraphLineAlpha":1
},
"chartCursor": {
"fullWidth":true,
"categoryBalloonDateFormat": "JJ:NN:SS, DD MMMM",
"cursorAlpha": 0.01,
"graphBulletAlpha": 10
},
"categoryField": "zaman",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
},
"export": {
"enabled": true,
"dateFormat": "YYYY-MM-DD HH:NN:SS"
}
});
chart.addListener("dataUpdated", zoomChart);
function zoomChart(){
chart.zoomToDates(new Date(2018, 0), new Date(2020, 0));
}
</script>
<!-- HTML -->
<div id="chartdiv"></div>
</tr>';
}
else
{
$result .='
<tr>
<td colspan="5">No Purchased Item Found</td>
</tr>';
}
$result .='</table>';
echo $result;
}
?>
<body>
</body>
</html>

Why html loads completely before loading datatable?

For downloading button I had refer page:
https://www.datatables.net/extensions/buttons/examples/initialisation/export.html
For server side I had refer page:
https://datatables.net/examples/data_sources/server_side.html
I had refer above page for making datatable to get data from database and download in different format. But the main problem is it first load the html table. after completely loading html table it shows the datatable which is noticeable for large no of rows. I have to get large no of rows to show in datatable and export the file in excel. Can anyone help me how can i load datatable without loading html table.
Here is my code
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- for button -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css">
<!-- for button -->
</head>
<body>
<table id="example" class="display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th style="text-align: center;">Model No</th>
<th style="text-align: center;">BIll NO</th>
<th style="text-align: center;">Name Of Party</th>
<th style="text-align: center;">Bill Miti</th>
<th style="text-align: center;">Invoice Date</th>
<th style="text-align: center;">IMEI No</th>
<th style="text-align: center;">Price</th>
<th style="text-align: center;"><div id="section_notTo_Print"> Edit </div></th>
</tr>
</thead>
<tbody>
<?php
include 'dbconnect.php';
//get records from database
$query = $con->query("SELECT * FROM salesreport ORDER BY id DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){ ?>
<tr>
<td style="text-align: center;"><?php echo $row['modelno']; ?></td>
<td style="text-align: center;"><?php echo $row['billno']; ?></td>
<td style="text-align: center;"><?php echo $row['nameOfParty']; ?></td>
<td style="text-align: center;"><?php echo $row['billMiti']; ?></td>
<td style="text-align: center;"><?php echo $row['invoiceDate']; ?></td>
<td style="text-align: center;"><?php echo $row['IMEINo']; ?></td>
<td style="text-align: center;"><?php echo $row['price']; ?></td>
<td style="text-align: center;"><div id="section_notTo_Print"> Edit </div></td>
<!-- <td><?php //echo $row['Quantity']; ?></td> -->
<!-- <td><?php //echo ($row['status'] == '1')?'Active':'Inactive'; ?></td> -->
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No distributor found.....</td></tr>
<?php } ?>
</tbody>
</table>
<!-- for exporting -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js">
</script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js">
</script>
<script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js">
</script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
// "serverSide": true,
// "ajax": "datatable2.php",
dom: 'lBfrtip',
buttons: [
{
extend: 'collection',
text: 'Export',
buttons: [
'copy',
'excel',
'csv',
'pdf',
'print'
]
}
]
} );
} );
</script>
<!-- for exporting -->
</body>
</html>
This code for your reference it`s sample code how to load table record from database in datatable
Viewfile
<table id="placeTable" class="table table-striped table-bordered responsive nowrap">
<thead class="">
<tr>
<th>Name</th>
<th>Location</th>
<th>Status</th>
<th>Action</th>
<th></th>
</tr>
</thead>
</table>
</div><!--table-responsive-->
<script>
jQuery(document).ready(function () {
jQuery('#placeTable').DataTable({
"oLanguage": {
"sProcessing": '<img alt src="<?php echo base_url('assets/images/loaders/CustomLoader.gif'); ?>" style="opacity: 1.0;filter: alpha(opacity=100);">'
},
"processing": true,
"serverSide": true,
"responsive": true,
"order": [[4, "DESC"]],
"ajax": {
url: "<?php echo site_url('admin/place/getPlace'); ?>",
},
"columns": [
{"taregts": 0, "data": "name"},
{"taregts": 1, "data": "location"},
{"taregts": 2,
"searchable": false,
"orderable": false,
"sClass": "text-center",
"render": function (data, type, row) {
var id = row.id;
if (row.is_active === '1') {
var out = ' <a class="btn btn-success statusenable" href="#" \n\ \n\
title="Click to Change status" data-href="<?php echo site_url('admin/place/change_status') ?>/' + id + '" data-toggle="modal" data-target="#confirm-status" title="Confirm">\n\
Enable</i></a> ';
return out;
} else if (row.is_active === '0') {
var out = ' <a class="btn btn-danger statusenable" href="#" \n\ \n\
title="Click to Change status" data-href="<?php echo site_url('admin/place/change_status') ?>/' + id + '" data-toggle="modal" data-target="#confirm-status" title="Confirm">\n\
Disable</i></a> ';
return out;
}
}
},
{"taregts": 3, "searchable": false,
"orderable": false,
"sClass": "text-center",
"render": function (data, type, row) {
var id = row.id;
return '<a class="actioncol cursor view" href=\'<?php echo site_url('admin/place/view'); ?>/' + id + '\'\n\
title="View"><i class="glyphicon glyphicon-eye-open"></i></a>\n\<a class="actioncol cursor view" href=\'<?php echo site_url('admin/place/edit'); ?>/' + id + '\'\n\
title="Edit"><i class="glyphicon glyphicon-edit"></i></a>';
}
},
{"taregts": 4, "visible": false,
render: function (data, type, row) {
return row.id;
}
}
]
});
});
</script>
Controller Place.php file
//get all place
public function getPlace() {
$columns = array('name', 'location','is_active','id','id');
$request = $this->input->get();
$condition = array();
$getfiled = "name,is_active,location,id";
echo $this->db_common->getDataTableSource('place', $columns, $condition, $getfiled, $request);
die();
}
model for database query common.php
/*
* This function is to create the data source of the Jquery Datatable
*
* #param $tablename Name of the Table in database
* #param $datatable_fields Fields in datatable that avalable for filtering
* #param $condition_array conditions for Query
* #param $data The field set tobe return to datatables
* #param $request The Get or Post Request Sent from Datatable
* #param $join_str Join array for Query
* #return JSON data for datatable
*/
function getDataTableSource($tablename, $datatable_fields = array(), $conditions_array = array(), $data = '*', $request, $join_str = array()) {
$output = array();
//Fields tobe display in datatable
$this->db->select($data);
//Making Join with tables if provided
if (!empty($join_str)) {
foreach ($join_str as $join) {
if (!isset($join['join_type'])) {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//COnditions for Query
if (!empty($conditions_array)) {
$this->db->where($conditions_array);
}
//Total record in query tobe return
$output['recordsTotal'] = $this->db->count_all_results($tablename, FALSE);
//Filtering based on the datatable_fileds
if ($request['search']['value'] != '') {
$this->db->group_start();
for ($i = 0; $i < count($datatable_fields); $i++) {
if ($request['columns'][$i]['searchable'] == true) {
$this->db->or_like($datatable_fields[$i], $request['search']['value']);
}
}
$this->db->group_end();
}
//Total number of records return after filtering not no of record display on page.
//It must be counted before limiting the resultset.
$output['recordsFiltered'] = $this->db->count_all_results(NULL, FALSE);
//Setting Limit for Paging
$this->db->limit($request['length'], $request['start']);
//ordering the query
if (isset($request['order']) && count($request['order'])) {
for ($i = 0; $i < count($request['order']); $i++) {
if ($request['columns'][$request['order'][$i]['column']]['orderable'] == true) {
$this->db->order_by($datatable_fields[$request['order'][$i]['column']] . ' ' . $request['order'][$i]['dir']);
}
}
}
$query = $this->db->get();
$output['draw'] = $request['draw'];
$output['data'] = $query->result_array();
return json_encode($output);
}`enter code here`

Check all checkboxes on the current page only in datatables

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);
});

bootstrap editable - how to transfer dropdown value to SQL table?

I am currently working on a project that shows data from an SQL table using bootstrap editable for live editing.
It works fine - changes are transferred to the SQL table. What is already working?:
Showing current value from SQL table
Providing a drop-down for selection
Transferring changed values to SQL table
-> BUT Part 3 (transferring changed value) is only working for free-text input (class xedit).
What I am looking for is the code for: transferring chosen value of drop-down-list to SQL-Table
Here is the HTML-code:
<?php
include("connect.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta charset="utf-8">
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div style="text-align:center;width:100%;font-size:24px;margin-bottom:20px;color: #2875BB;">EDIT YOUR CHARACTERS</div>
<div class="row">
<table class= "table table-striped table-bordered table-hover">
<thead>
<tr>
<th colspan="1" rowspan="1" style="width: 180px;" tabindex="0">NAME</th>
<th colspan="1" rowspan="1" style="width: 220px;" tabindex="0">ROLE</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">SECOND ROLE</th>
</tr>
</thead>
<tbody>
<?php
$query = mysql_query("SELECT * FROM characters");
$i=0;
while($fetch = mysql_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td class="xedit" id="'.$fetch['id'].'" key="name">'.$fetch['name'].'</td>
<td class="xedit" id="'.$fetch['id'].'" key="role">'.$fetch['role'].'</td>
<td class="xedit2" id="'.$fetch['id'].'" key="secondrole">'.$fetch['secondrole'].' </td>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/bootstrap-editable.js" type="text/javascript"></script>
<script>
$(function(){
$('.rolestatus').editable({
source: [
{value: 1, text: 'DD'},
{value: 2, text: 'HEAL'},
{value: 3, text: 'TANK'}
]
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var key = $(this).closest('.editable-container').prev().attr('key');
var x = $(this).closest('.editable-container').prev().attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('.editable-container').prev().text(y);
$.ajax({
url: "process.php?id="+x+"&data="+y+'&key='+key,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
</div>
</body>
</html>
Here is the process.php code
<?php
include("connect.php");
if($_GET['id'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
if(mysql_query("update characters set $key='$data' where id='$id'"))
echo 'success';
}
?>
So does anybody know how I can transfer the chosen dropdown-value (class -> xedit2) to SQL table?
Hope you can help!
Not sure exacly how x-editable works
But in first look i think that the type of your ajax should be "POST" if you want to update some data. And in my opinion you have syntax error in your sql query near "$key"

Categories