Google Chart Drilldown based on javascript search - javascript

I have a javascript search bar. My output gets displayed in the table form and when I do a javascript search, it shows me the result of my search. I need my graph to also show only the result of the search when i do a search in the search bar.
<body>
<?php
$colors = array('#e2431e', '#f1ca3a', '#6f9654', '#1c91c0','#4374e0', '#5c3292', '#572a1a', '#999999', '#1a1a1a','red','blue','yellow','green', 'darkgreen','pink');
//initalizing the query
$id = $_GET['id'];
$query = "SELECT * FROM new_default_reports WHERE id = '$id'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
$row['sql_statement'] = stripslashes($row['sql_statement']);
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
autoOpen: false,
title: "<?php echo $row['graph_title']; echo ' - Update/Delete';?>",
width: 800,
height: 550,
zIndex:'2000000'
});
$("#btnShow").click(function () {
$('#dialog').dialog('open');
});
});
</script>
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
//header("Refresh: 0; url=previewgraphs.php?id=".$id);//not needed
$id = $_GET['id'];
$query = "SELECT * FROM new_default_reports WHERE id = '$id'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
$row['sql_statement'] = stripslashes($row['sql_statement']);
}
?>
<?php
if (isset($_POST['delete'])){
$query = "UPDATE new_default_reports SET deleted = 1 where id = $id";
$result = $conn->query($query);
header('Location: defaultreports.php');
}
?>
<br><input type="button" id="btnShow" class = "form-control" style="margin-top:12%;width:200px;border:2px solid darkgray;font-weight:bold;background-color:lightgray;" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
<input type="submit" name = "delete" class="classname" value = "DELETE">
</form>
</div>
<br>
<div class="col-md-12">
<?php if(isset($_REQUEST['notify'])){ ?>
<div class="alert alert-success fade in">
×
A New Graph <?php echo $row['graph_title']; ?> has been created.
</div>
<?php } ?>
<?php
$query = stripslashes($row['sql_statement']);
$result = $conn_temp->query($query);
//$row1 = $result->fetch_assoc();
//generating graph now
$x_axis = str_replace('`', '', $row['x_axis']);
$y_axis = str_replace('`', '', $row['y_axis']);
?>
<script type="text/javascript">
google.load('visualization', '1.1', {'packages':['corechart','wordtree','gantt']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
<?php if($row['type_of_graph']==6){ ?>
data.addColumn('string', '<?php echo $x_axis ?>');
data.addColumn('string', '<?php echo $y_axis ?>');
data.addColumn('date', 'Start Date');
data.addColumn('date', 'End Date');
data.addColumn('number', 'Duration');
data.addColumn('number', 'Percent Complete');
data.addColumn('string', 'Dependencies');
data.addRows([
<?php
$temp = 'null';
$count = 1;
while($row1 = $result->fetch_assoc()){
?>
['<?php echo $row1["$x_axis"] ?>','<?php echo $row1["$y_axis"] ?>', null, new Date(2015, 0, <?php echo $count ?>),daysToMilliseconds(<?php echo $count ?>), <?php echo $count++ ?>, <?php
if($temp=='null') {
?>null
<?php
}else{
echo '"'.$temp.'"';
} ?>],
<?php
$temp = $row1["$x_axis"];
} ?>
]);
<?php }else{ ?>
data.addColumn('string', '<?php echo $x_axis ?>');
data.addColumn('number', '<?php echo $y_axis ?>');
data.addColumn({'type': 'string', 'role': 'style' });
data.addColumn({'type': 'string', 'role': 'tooltip'});
data.addRows([
<?php
$count = 1;
while($row1 = $result->fetch_assoc()){
// print_r($row1);
// echo $x_axis.' '.$row1["$x_axis"].' '.$y_axis.' '.$row1["$y_axis"];
if($count > 10)
$count = 1;
?>
['<?php echo $row1["$x_axis"] ?>',<?php echo $row1["$y_axis"] ?>,'<?php echo $colors[$count++] ?>', '<?php $float = floatval($row1["$y_axis"]); if($float && intval($float) != $float && strlen($float) > 3 && strpos($row1["$y_axis"],"-") == false && strpos($key,"sgd") !== false){ echo $row1["$x_axis"]; echo " : " ; $yourval = number_format($row1["$y_axis"],2); echo "$".$yourval;} elseif ($float && intval($float) == $float && strlen($float) > 3){echo $row1["$x_axis"]; echo " : " ; echo number_format($row1["$y_axis"],2);} else{echo $row1["$x_axis"]; echo " : " ; echo number_format($row1["$y_axis"]);}?>' ],
<?php } ?>
]);
<?php } ?>
// Set chart options
var options = {height: 'auto',
backgroundColor: 'transparent',
chartArea: {
backgroundColor: 'transparent'
},
width : 'auto',
title: '<?php echo $row["graph_title"];?>',
tooltip : {trigger: 'selection', isHtml: true},
is3D: true,
legend: 'none',
vAxis: {title: '<?php echo $row ["y_axis"] ?>'}, //yaxis
hAxis: {title: '<?php echo $row ["x_axis"] ?>'}, //xaxis
bar: { groupWidth: '40%' },
vAxis: {format: '#,###.##'}
};
// Instantiate and draw our chart, passing in some options.
<?php if($row['type_of_graph']==1) { ?>
var chart = new google.visualization.LineChart(document.getElementById('container1'));
<?php }elseif($row['type_of_graph']==2){ ?>
var chart = new google.visualization.PieChart(document.getElementById('container1'));
<?php }elseif($row['type_of_graph']==3){ ?>
var chart = new google.visualization.ColumnChart(document.getElementById('container1'));
<?php }elseif($row['type_of_graph']==4){ ?>
var chart = new google.visualization.AreaChart(document.getElementById('container1'));
<?php }elseif($row['type_of_graph']==5){ ?>
var chart = new google.visualization.WordTree(document.getElementById('container1'));
<?php }elseif($row['type_of_graph']==6){ ?>
var chart = new google.visualization.GanttChart(document.getElementById('container1'));
<?php } ?>
chart.draw(data, options);
//set default section for one column
chart.setSelection([{row:0, column:1}]);
}
</script>
<div id="container1" style="width:100%;"></div>
<style>div.google-visualization-tooltip { background-color: #CCCC99; font-weight:bold;border:2px solid darkgray;}</style>
<div class="panel panel-default" style="margin-top:2%;">
<div class="panel-body">
<table border="0" cellpadding="5" cellspacing="5" style="width:100%;">
<tbody>
<tr>
<td>Select Column :</td>
<td>
<select name="select_column" id="select_column" class="form-control">
<option value="">NULL</option>
<?php
//generate query and doing a search
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{
foreach((array)$row1 as $key=>$val)
{ ?>
<option value="<?php echo $key ?>"><?php echo $key ?></option>
<?php }
break;
}
?>
</select>
</td>
<td>Enter value to search :</td>
<td>
<input type="text" name="select_value" id="select_value" value="" class="form-control">
</td>
</tr>
</tbody>
</table>
<hr>
<table class="table table-striped table-bordered table-hover" id="dataTable_table">
<thead>
<tr>
<?php
//generate query
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{
foreach((array)$row1 as $key=>$val)
{
?>
<th><?php echo $key ?></th>
<?php
}
break;
}
?>
</tr>
</thead>
<tbody>
<?php
//generate query
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{ ?>
<tr>
<?php
foreach((array)$row1 as $key=>$val) //generate all the columns
{ ?>
<th><?php
$float = floatval($val);//checking for decimal if it is present
if($float && intval($float) != $float && strlen($float) > 3 ){ //checking for the criteria to place decimalpoints
$yourval = number_format($float,2); //placing it in 2 decimal points
echo $yourval;
}
elseif($float && intval($float) != $float && strlen($float) > 3 && strpos($val,'-') == false){ //checking for the criteria to place decimalpoints
$yourval = number_format($float,2); //placing it in 2 decimal points
echo $yourval;
}
elseif ($float && intval($float) == $float && strlen($float) > 3 && strpos($val,'-') == false){
$yourval = number_format($float,2);
echo $yourval;
}
else{
echo $val; //if does not fit the criteria then place just show the value
}
?></th>
<?php
} ?>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<style>
#dataTable_table thead {
background-color:#D2DCDF;
font-weight:bold;
text-transform:uppercase;
border:2px inset #D2DCDF;
padding:5px;
}
</style>
<link href="scripts/dataTables/dataTables.bootstrap.css" rel="stylesheet">
<script src="scripts/dataTables/jquery.dataTables.js"></script>
<script src="scripts/dataTables/dataTables.bootstrap.js"></script>
<script>
$.fn.dataTable.ext.search.push(//search portion for graphs
function( settings, data, dataIndex ) {
var select_value = $('#select_value').val();
var select_column = $('#select_column').val();
var column_index = '';
//var column = data[1] || 0; // use data for the age column
if ( select_value == '' || select_column == '' )
{
return true;
}
else {
//get the column name of data table
var column = 0;
$('#dataTable_table thead tr th').each(function(){
if( $(this).text() == select_column.toString())
{
return false;
}
column = column + 1;
});
column = data[column] || 0;
if(column!==0 && column.toLowerCase().indexOf(select_value.toString().toLowerCase()) >= 0)
{
return true;
}
}
return false;
}
);
$(document).ready( function () {
$('#dataTable_table').dataTable( {
"bSort": false
} );
} );
$.fn.dataTableExt.sErrMode = 'throw';
$(document).ready(function () {
var table = $('#dataTable_table').DataTable();
$('#select_value').keyup( function() {
table.draw();
});
});
</script>
</body>

Related

Pagination does not work on page2 in php web page

Can someone help me on pagination syntax for php webpage. I have a set a pagination code to display 20 records per page. The records are displaying based on 'start date' and 'end date'.
The issue is, it works on page 1 but when I click on page 2 in pagination then it won't work. I assume the values of $_POST['startdate'] and $_POST['enddate] are not forwarding on page2.
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="multitab/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
.inline{
display: inline-block;
float: right;
margin: 20px 0px;
}
input, button{
height: 34px;
}
</style>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<table>
<tr>
<td><b>Start date:</b></td>
<td><input type="date" id="startdate" name="startdate" size="10"> </td>
<td><b>End date:</b></td>
<td><input type="date" id="enddate" name="enddate" size="10" max=<?php echo date('Y-m-d');?>></td>
<td><input type="submit" value="Search" name="Search" onClick="return check()"></td>
</tr>
</table>
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abc_db",$con);
$limit = 20;
if (isset($_GET["page"])) {
$pn = $_GET["page"];
}
else {
$pn=1;
};
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
$start_from = ($pn-1) * $limit;
$serial = (($pn-1) * $limit) + 1;
$today1= date("Y/m/d");
$days14_ago = date('Y/m/d', mktime(0, 0, 0, date("m") , date("d") - 14, date("Y")));
if ($startdate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$startdate1' LIMIT $start_from, $limit";
} else if ($enddate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$enddate1' LIMIT $start_from, $limit";
} else {
$sql = "SELECT * FROM hd where datearrival between '$days14_ago' and '$today1' LIMIT $start_from, $limit";
}
if (($startdate !=Null) && ($enddate !=Null)) {
$sql = "SELECT * FROM hd where datearrival between '$startdate1' and '$enddate1' LIMIT $start_from, $limit";
}
$rs_result = mysql_query ($sql);
?>
<div class="container">
<button style="height:25px;width:70px;" onclick="window.location.reload(true);">Refresh</button>
<br>
<div>
<font face='cambria'><p><span style="display:inline-block; margin-left: 650px; ">
</span></p> </font>
<font face="Cambria" size="2"> <table class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th width="5%" valign="top">Sr#</th>
<th width="10%" valign="top">Date arrival</th>
<th width="10%" valign="top">Pno</th>
<th width="10%" valign="top">First name</th>
<th valign="top"></th>
<th valign="top"></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
$pno1=$row['pno'];
$datearrival1=$row['datearrival'];
$sr_num = $serial++;
?>
<tr>
<td><?php echo $sr_num; ?></td>
<td><?php echo date("d/m/Y", strtotime($row['datearrival'])); ?></td>
<td><?php echo $row["pno"]; ?></td>
<td><?php echo $row["first_name"]; ?></td>
<td><p align="center">edit</font></td>
<td><p align="center">delete</font></td>
</tr>
<?php
};
?>
</tbody>
</table>
</font>
<div>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM hd where datearrival between '$startdate1' and '$enddate1'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$k = (($pn+4>$total_pages)?$total_pages-4:(($pn-4<1)?5:$pn));
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."'> >> </a></li>";
}
?>
</ul>
<div class="inline">
<input id="pn" type="number" min="1" max="<?php echo $total_pages?>"
placeholder="<?php echo $pn."/".$total_pages; ?>" required>
<button onclick="go2Page();">Go</button>
</div>
</div>
</div>
</div>
<script>
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'qm.php?page='+pn;
}
/* start and end date- validation checks */
function check(){
var startdatea=document.getElementById("startdate").value;
var enddatea=document.getElementById("enddate").value;
if(Date.parse(startdatea)>Date.parse(enddatea)){
alert("Please select a different End Date.");
return false;
}
}
</script>
</body>
</html>
$_POST superglobal variable is populated by PHP when a POST HTTP request is processed. This is the case on the request for page 1.
However, your go2page() function is mutating location.href, which generates a GET HTTP request, and so does pagination links.
You should append your startdate and enddate params to the pagination URLs, to forward your params to the next/previous requests :
qm.php?page=<YOUR-PAGE-NUMBER>&startdate=<YOUR-START-DATE>&enddate=<YOUR-END-DATE>';
And use $_GET['startdate'] and $_GET['enddate] to retrieve those when processing GET requests.
More about $_POST https://www.php.net/manual/en/reserved.variables.post.php
More about GET AND POST HTTP requests : https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
There's an error in your isset($_POST['Search'])
your code:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
possible working solution:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
Though I didn't try it yet, but I assume this is the cause, pagination in page2 will not work since the code is not executed after the error which is the pagination for page2.
EDIT: The . fixes things.
echo "Start date : ".$startdate1", ";
is different than
echo "Start date : ".$startdate1.", ";
Add values of your $_POST inside links and use them as $_GET so you would use both.
$startdate1=$enddate1=null; //to hide notice
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
} else if (!empty($_GET['startdate']) && !empty($_GET['enddate'])){
$startdate1 = $_GET['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_GET['enddate'];
echo "End date : ".$enddate1;
}
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
For your need:
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1&startdate=".startdate1."&enddate=".$enddate1."'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."&startdate=".startdate1."&enddate=".$enddate1."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."&startdate=".startdate1."&enddate=".$enddate1."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."&startdate=".startdate1."&enddate=".$enddate1."'> >> </a></li>";
}
That would help you to move dates to next page.
You need to set it to all paging links. Also you can make extra if statement to not pass empty GET
EDIT:
As I already told: You need to set it to all paging links. Also you can make extra if statement to not pass empty GET (that includes javascript)
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'teztz.php?page='+pn+'&startdate=<?=startdate1;?>&enddate=<?=$enddate1;?>';
}

how to write javascript which create fixedheader for each table separately

There is a self-written website on WordPress tarifes. I made a script that searches for each copy of the thead table and makes it fixed to the fixed_table_header table, but here's the problem when the same shortcode makes a new table for each one and the same thead, help you figure out how to add or change the script so that the header was fixed for each table separately
<?php
/*====================================================SHORTCODES EXEL=========================================================*/
public function show_mps_excel($atts){
$atts = shortcode_atts( array(
'name' => 'express_import',
'sheet' => 0,
'class' => '',
), $atts );
extract($atts);
?>
<?php $mps_option = get_option('gamma_mps'); ?>
<?php if(isset($mps_option[$name]['sheet'.$sheet])): ?>
<?php ob_start(); ?>
<div class="container-fluid block-content">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 welcome-text">
<!-- <table class="table table-hover table-bordered taxes" style="margin-top: -25px"> -->
<?php if($name != 'zones'): ?>
<?php $this->full_table($mps_option, $name, $sheet, $class); ?>
<?php else: ?>
<?php $this->half_table($mps_option, $name, $sheet, $class, 0, 118); ?>
<?php $this->half_table($mps_option, $name, $sheet, $class, 117, 234); ?>
<?php endif; ?>
<?php if(false): ?>
<h5>Загрузить таблицу в .XLSX: <a class="btn btn-success" href="<?php echo $mps_option[$name]['download_url']; ?>">Загрузить</a></h5>
<?php endif; ?>
</div>
</div>
</div>
<?php $html = ob_get_clean(); ?>
<?php endif; ?>
<?php
return $html;
}
private function full_table($mps_option, $name, $sheet, $class){
?>
<table class="table table-hover table-bordered mps_xls sheet-<?php echo $sheet; ?> <?php echo $name; ?> <?php echo $class; ?>" style="margin-top: -25px">
<?php foreach ($mps_option[$name]['sheet'.$sheet] as $row => $cols): ?>
<?php if(!$cols['A'] && !$cols['B'] && !$cols['C']) continue; ?>
<?php echo $row==1 ? '<thead><tr>':'<tr>'; ?>
<?php foreach ($cols as $col): ?>
<?php echo $row==1 ? '<th>':'<td>'; ?>
<?php echo $col; ?>
<?php echo $row==1 ? '</th>':'</td>'; ?>
<?php endforeach; ?>
<?php echo $row==1 ? '</tr></thead>':'</tr>'; ?>
<?php endforeach; ?>
</tbody>
</table>
<?php
}
private function half_table($mps_option, $name, $sheet, $class, $start_row, $end_row){
$count = 1;
?>
<div class="col-sm-6 col-md-6 col-lg-6 welcome-text">
<table class="table table-hover table-bordered mps_xls sheet-<?php echo $sheet; ?> <?php echo $name; ?> <?php echo $class; ?>" style="margin-top: -25px">
<?php foreach ($mps_option[$name]['sheet'.$sheet] as $row => $cols): ?>
<?php if($count <= $start_row && $count > 1) {$count++; continue;} ?>
<?php if($count >= $end_row) break; ?>
<?php echo $row==1 ? '<thead><tr>':'<tr>'; ?>
<?php foreach ($cols as $col): ?>
<?php echo $row==1 ? '<th>':'<td>'; ?>
<?php echo $col; ?>
<?php echo $row==1 ? '</th>':'</td>'; ?>
<?php endforeach; ?>
<?php echo $row==1 ? '</tr></thead>':'</tr>'; ?>
<?php $count++; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
}
?>
(function($) {
$(document).ready(function() {
var table = $('table'),
thead = table.find('thead'),
fixed_thead,
fixed_table = $('<table />', {
'cellpadding': 5,
'cellspacing': 0,
'border': 1,
'id': 'fixed_table_header'
}),
fixed_table_wrapper = $('<div />', {
'height': 400,
'css': {
'overflow': 'auto'
}
});
table.before(fixed_table);
thead.find('td').each(function() {
$(this).css('width', $(this).width());
});
fixed_thead = thead.clone();
fixed_table.append(fixed_thead);
thead.hide();
table.wrap(fixed_table_wrapper);
// align the new table header with the original table
fixed_table.css('left', (fixed_table.offset().left - table.offset().left) * -1);
});
})(jQuery);
If I understand your question correctly, you target only the first table by using var table = $('table'),. You need to run the manipulation on each table so your code should look something like:
(function($) {
$(document).ready(function() {
$('table').each(function() {
var table = $(this),
thead = table.find('thead'),
fixed_thead,
fixed_table = $('<table />', {
'cellpadding': 5,
'cellspacing': 0,
'border': 1,
'id': 'fixed_table_header'
}),
fixed_table_wrapper = $('<div />', {
'height': 400,
'css': {
'overflow': 'auto'
}
});
table.before(fixed_table);
thead.find('td').each(function() {
$(this).css('width', $(this).width());
});
fixed_thead = thead.clone();
fixed_table.append(fixed_thead);
thead.hide();
table.wrap(fixed_table_wrapper);
// align the new table header with the original table
fixed_table.css('left', (fixed_table.offset().left - table.offset().left) * -1);
});
});
})(jQuery);
This case is similar to the way a jQuery plugin should be written and the solution is similar too: https://learn.jquery.com/plugins/basic-plugin-creation/#using-the-each-method

How to fix ReferenceError jQuery?

I cant find the error from my code,took me hours trying to figure it out but still cant make it work.
I've checked on the browser console and it shows as ascreenshot below :
Here's my code :
<?php
session_start();
use Phpml\Classification\SVC;
use Phpml\SupportVectorMachine\Kernel;
include "koneksi.php";
include "function.php";
if(!isset($_SESSION['username'])){
header('location:login.php');
}else{
$username = $_SESSION['username'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Pelatihan SVM</title>
<link rel="stylesheet" type="text/css" href="styles/2nd.css">
<script src="jquery-3.1.1.min.js"></script>
<?php
cekUser();
?>
</head>
<body>
<div class="tab">
<button class="menuTab" onclick="switchMenu(event, 'useDatabase')" id="admin">Data Mentah</button>
<button class="menuTab" onclick="switchMenu(event, 'term')" id="nonAdmin">Data Feature Selection</button>
</div>
<div id="useDatabase" class="tabContent">
<?php
$start=0;
$limit=100;
if(isset($_GET['id'])){
$id=$_GET['id'];
$start=($id-1)*$limit;
}else{
$id=1;
}
$q = mysqli_query($db, "SELECT * FROM dataset_latih LIMIT $start, $limit")or die(mysqli_error($db));
$no=$start+1;
$q1=mysqli_query($db, "SELECT COUNT('label') AS 'label positif' FROM dataset_latih WHERE label='positif'");
$row=mysqli_fetch_assoc($q1);
$positif=$row['label positif'];
$q2=mysqli_query($db, "SELECT COUNT('label') AS 'label negatif' FROM dataset_latih WHERE label='negatif'");
$row2=mysqli_fetch_assoc($q2);
$negatif=$row2['label negatif'];
?>
<h2 align="center">Dataset Latih</h2>
<h3 style="text-align: center;">Positif : <?php echo $positif; ?> | Negatif : <?php echo $negatif; ?> | Total : <?php echo $positif+$negatif; ?></h3>
<table border=1 align="center" class="h-header">
<thead>
<tr>
<th width="25">No.</th>
<th width="1200">Komentar</th>
<th width="70">Kelas</th>
</tr>
</thead>
<?php
while ( $result = mysqli_fetch_assoc($q) ) {
echo "<tr>";
echo "<td>" . $no . "</td>";
echo "<td class='kiri'>" . $result['komentar'] . "</td>";
echo "<td>" . $result['label'] . "</td>";
echo "</tr>";
$no++;
}
?>
</table>
<div class='wrapper'>
<button class='button' id="prosesData">Proses</button>
</div>
<div class="paging" style="text-align: center;">
<?php
$rows=mysqli_num_rows(mysqli_query($db, "SELECT * FROM dataset_latih"));
$total=ceil($rows/$limit);
if ($id>1) {
echo "<a href='?id=".($id-1)."' class='button' id='table1'>Previous </a>";
}
for ($i=1; $i <=$total ; $i++) {
if ($i==$id) {
echo "<span class='active'>$i</span>";
}else{
echo "<a href='?id=".$i."' id='table1'> ".$i." </a>";
}
}
if ($id!=$total) {
echo "<a href='?id=".($id+1)."' class='button' id='table1'> Next</a>";
}
?>
</div>
</div>
<div id="term" class="tabContent">
<h2 align="center">Term Latih</h2>
<?php
$start=0;
$limit=100;
if(isset($_GET['id1'])){
$id1=$_GET['id1'];
$start=($id1-1)*$limit;
}else{
$id1=1;
}
$q = mysqli_query($db, "SELECT * FROM data_latih_ready LIMIT $start, $limit")or die(mysqli_error($db));
$no=$start+1;
$rowPersentase = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM selected_feature"))or die(mysqli_error($db));
$persentase = $rowPersentase['persentase'];
$td1 = '';
$td2 = '';
$td3 = '';
while ($row1 = mysqli_fetch_assoc($q)) {
$td1 .= "<td>$no</td>";
$td2 .= "<td>".$row1['term']."</td>";
$td3 .= "<td>".$row1['tf_idf_normalisasi']."</td>";
$no++;
}
?>
<h3 style="text-align: center;">Feature Selection : <?php echo $persentase; ?>%</h3>
<div class="v-header">
<table border="1" align="center" cellpadding="20">
<thead>
<tr>
<th>No.</th>
<?php echo $td1; ?>
</tr>
<tr>
<th>Term</th>
<?php echo $td2; ?>
</tr>
<tr>
<th>Normalisasi TF.IDF</th>
<?php echo $td3; ?>
</tr>
</thead>
</table>
</div>
<!-- <br> -->
<div class="paging2" style="text-align: center;">
<?php
$rows=mysqli_num_rows(mysqli_query($db, "SELECT * FROM data_latih_ready"));
$total=ceil($rows/$limit);
if ($id1>1) {
echo "<a href='?id1=".($id1-1)."' class='button' id='table2'>Previous </a>";
}
for ($i=1; $i <=$total; $i++) {
if ($i==$id1) {
echo "<span class='active'>$i</span>";
}else{
echo "<a href='?id1=".$i."' id='table2'> ".$i." </a>";
}
}
if ($id1!=$total) {
echo "<a href='?id1=".($id1+1)."' class='button' id='table2'> Next</a>";
}
?>
<div class="btnFeature">
<ul>
<li>
<button class="button" onclick="train();">Latih SVM</button>
</li>
<li>
<button class="button" id="featureSelection">Feature Selection</button>
</li>
</ul>
</div>
</div>
</div>
<div class="info" align="center">
<p>Tabel di atas merupakan tabel term dengan nilai yang telah disesuaikan dengan nilai <strong>Feature Selection</strong><br>
Silahkan menekan tombol <strong>Latih SVM</strong> jika <strong>Feature Selection</strong> sudah sesuai kebutuhan.
</p>
</div>
<?php
$cek = cekTabelToken();
?>
<script type="text/javascript">
// biar otomatis tab aktif waktu halaman svmLatih.php dibuka
document.getElementById("admin").click();
$(".info").hide();
$("#admin").click(function(){
$(".info").hide();
});
$("#nonAdmin").click(function(){
$(".info").show();
});
// var untuk cek tabel term kosong gk
var cek = "<?php echo "$cek"; ?>"
$("#prosesData").click(function(){
// kalau tabel term gk kosong, alert mau proses ulang gk
if (cek > 0) {
var conf = confirm("Preprocessing data latih sudah pernah dilakukan.\nIngin memproses ulang ?");
if (conf == true) {
$.ajax({
url: "action.php",
data:{action: "prosesUlangDataLatih"},
type: "POST",
// kalau berhasil kasih alert lalu redirect
success: function(){
alert("Preprocessing ulang selesai.");
setTimeout(function(){
window.location.href = 'featureSelection.php';
},1000);
}
});
}
}else{
// kalau tabel term kosong ya langsung aja proses
$.ajax({
url: "action.php",
data:{action: "preprocessing"},
type: "POST",
// kalau berhasil kasih alert lalu redirect
success: function(){
alert("Preprocessing selesai.");
setTimeout(function(){
window.location.href = 'featureSelection.php';
},1000);
}
});
}
});
// fungsi untuk switch tab
function switchMenu(evt, selectedMenu){
var i, tabContent, menuTab;
tabContent = document.getElementsByClassName("tabContent");
for (i = 0; i < tabContent.length; i++) {
tabContent[i].style.display = "none";
}
menuTab = document.getElementsByClassName("menuTab");
for(i = 0; i < menuTab.length; i++){
menuTab[i].className = menuTab[i].className.replace(" active", "");
}
document.getElementById(selectedMenu).style.display = "block";
evt.currentTarget.className += " active";
}
// tombol feature selection
$("#featureSelection").click(function(){
window.location = "featureSelection.php";
});
// tombol latih SVM
function train(){
$.ajax({
type: "POST",
url: "action.php",
data:{
action: "trainDatabase"
},
success: function(){
alert("Model SVM sudah dibuat.");
},
error: function(){
alert("Error");
}
});
}
</script>
</body>
</html>
I hope someone can help me to find the error, I've been stuck here for hours. Thank you.

Updating quantity in cart table

I want that update button should be in that field which I choose.But it appears only in first row and is updating for first row quantity field.
<form action="cart.php?action=update" method="post">
<table>
<tr>
<th colspan="2">ITEM</th>
<th>QUANTITY</th>
<th>PRICE</th>
<th>SUBTOTAL</th>
<th>REMOVE</th>
</tr>
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$b = 0;$c = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<tr>
<td rowspan="3"><img src="upload/<?php echo $row2['pimage']; ?>" height="50px" width="50px"></td>
<td rowspan="3"><?php echo $row2['pname']; ?></td>
<td rowspan="3">
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit()">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;" type="submit" name="sub1" id="sub1" value="UPDATE">
<input type="hidden" name="hidcartid" value="<?php echo $row['cart_id'] ?>"/>
<input type="hidden" name="hidproductid" value="<?php echo $row['product_id']; ?>"/>
<script>
function showsubmit()
{
document.getElementById("sub1").style.visibility = "visible";
}
</script>
</td>
<td>Price:<?php echo $sp = $row2['psellingprice']; ?></td>
<?php
$total = $sp * $qty;
?>
<td rowspan="3">
<?php
echo $t = $total;
$b = $b + $t;
?></td>
<td rowspan="3">REMOVE</td>
</tr>
<?php
$action = ( array_key_exists( 'action', $_REQUEST) ? $_REQUEST['action'] : "" );
if($action =="delete")
{
deletecart($_REQUEST['cid']);
}
if($action=="update")
{
echo "update function called";
updatecart();
echo "update function executed";
}
?>
<tr>
<td>Selling Price:<?php echo $p = $row2['pprice']; ?></td>
</tr>
<tr>
<td>You Saved:
<?php
$d = $row2['pdiscount'];
$s = ($p*$d)/100;
echo $q = $s * $qty;
$c = $c + $q;
?> rs.</td>
</tr>
<?php
}
}
?>
</table>
and cart2.php
<?php
function deletecart($cartid)
{
include 'connection.php';
$sql1="delete from cart where cart_id=$cartid";
$executequery = mysqli_query($con,$sql1);
header('location:cart.php');
}
function updatecart()
{
include 'connection.php';
$cartId = $_POST['hidcartid'];
$productId = $_POST['hidproductid'];
$newqty = $_POST['newqty'];
echo("inside update function");
// update product quantity
$sql = "UPDATE cart
SET quantity = $newqty
WHERE cart_id = $cartId";
mysqli_query($con,$sql);
header('location:cart.php');
}?>
For row onw everything is fine.But for row2 update button appears in row1 and not updating at all.
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit(<?php echo $row['cart_id'] ?>)">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
<script>
function showsubmit(id)
{
document.getElementById("sub_"+id).style.visibility ="visible";
}
</script>

Add to cart with ajax in codeigniter

I'm trying add to cart using CodeIgniter and it is working fine but, when I want to do the same through ajax its getting some problem. Can you please look at my codes and tell me where do I get some mistakes? I'm confused how to use ajax to call the add function of the controller . What should I add or do in the ajax code to make this function work?
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $("#myform").serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping/add",
type: "POST",
data: insert_data,
success: function(response)
{
if (response)
{
//window.location.replace("http://127.0.0.1/codeigniter_cart2/index.php/shopping");
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
}
else{
alert('sorry');
}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping/remove/all'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
Now my controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_views', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
redirect('shopping');
return TRUE;
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
// Destroy data which store in session.
$this->cart->destroy();
}else{
// Destroy selected rowid in session.
$data = array(
'rowid' => $rowid,
'qty' => 0
);
// Update cart data, after cancle.
$this->cart->update($data);
}
// This will show cancle data in cart.
redirect('shopping');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping');
}
}
How should I apply this code to ajax?
Thanks for the help.
it's not necessary to use "success:"
However if you want to check error or debug
1) press F12 on Browser to open Developer Mode
2) do action (add cart)
3) on tab "Network" find your ajax request and see your error
Modify your add() function as follows:
function add(){
$insert_data = array('k1' => 'v1', 'k2' => 'v2');
$success = $this->cart->insert($insert_data);
if($success){
$res = array('status' => 200, 'msg' => 'success', 'somekey' => 'somevalue');
}else{
$res = array('status' => 500, 'msg' => 'database err');
}
echo json_encode($res);
}
Now the add() function has responded the ajax request with some json-formated data, you can parse the response data in javascript. The (success:) function should be like this:
function(response) {
if (response){
var res = JSON.parse(response);
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
}else{
//error handler
alert(res.msg);
}
}else{
alert('sorry');
}
});
function __construct(){
parent::__construct();
$this->load->library(array('session','cart'));
$this->load->library('');
$this->load->helper('url');
$this->load->database();
}
public function product_list(){
$this->db->select('*');
$this->db->from('product');
$this->db->order_by('product_id','desc');
$rs = $this->db->get();
return $rs->result_array();
}
public function product_byId($pid){
$this->db->select('*');
$this->db->from('product');
$this->db->where('product_id',$pid);
$rs = $this->db->get();
return $rs->row_array();
}
Download full code from here http://phpcooker.com/codeigniter-shopping-cart

Categories