I have a table fetching its data from database
I want to make pagination for table but without refreshing the page
my table code:
<?php
<table id="table2" class="table table-hover table-mc-light-blue ">
<thead>
<tr>
<th>#</th>
<th>اسم المطرب</th>
<th>عدد الاغاني</th>
<th>تعديل</th>
</tr>
</thead>
<tbody class="searchable" >
<?php
$artistquery= mysqli_query($conn,"SELECT * FROM `artist` ORDER BY `artistID` DESC ");
$num=1;
$x=0;
while($listartist = mysqli_fetch_assoc($artistquery)){
$songquery= mysqli_query($conn,"SELECT * FROM `songs` WHERE `artist` = '$listartist[artistname]' ");
$songsnumber = mysqli_num_rows($songquery);
$x+=0.1;
echo'
<tr class="animated bounceIn " style=" animation-delay:'.$x.'s;">
<td data-title="#"></td>
<td data-title="اسم المطرب"></td>
<td data-title="عدد الاغاني"></td>
<td data-title=""></td>
</tr> ';}
?>
NOTE: I tried DataTables.js but i did know how to remove the filter and show labels.
is there any different way to do it ?
I dont fully comprehend your query so I'll stick to the pagination. Lets Say you want to show 10 items at a time and you are using next and prev as pagination buttons, you can render the first view using LIMIT 10 in your query or using array_slice($mysql_result,0,10). I have this downloaded json files containing zips (countries and code), that is what I used to test it. the next and prev totally perfect but it works.
<?php
$mysql_result = (array) json_decode(file_get_contents('zips'));
if(isset($_GET['ajax'])){
header('content-type: application/json');
$_GET['offset'] = isset($_GET['offset'])?$_GET['offset']:0;
echo json_encode(array_slice($mysql_result,$_GET['offset'],10));
exit;
}
$ar = array_slice($mysql_result,0,10);//or add LIMIT 10 in sql query
?>
<table border="on" width="100%">
<tbody id="songartiststuff">
<?php foreach($ar as $k => $r)://initial render?>
<tr>
<td data-replace="code"><?=$r->code?></td>
<td data-replace="country"><?=$r->country?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<center>
<button data-next="10">Next</button>
<button data-prev="0">Prev</button>
</center>
<script src="jquery.js"></script>
<?php
$mysql_result = (array) json_decode(file_get_contents('zips'));
if(isset($_GET['ajax'])){
header('content-type: application/json');
$_GET['offset'] = isset($_GET['offset'])?$_GET['offset']:0;
echo json_encode(array_slice($mysql_result,$_GET['offset'],10));
exit;
}
$ar = array_slice($mysql_result,0,10);//or add LIMIT 10 in sql query
?>
<table border="on" width="100%">
<tbody id="songartiststuff">
<?php foreach($ar as $k => $r)://initial render?>
<tr>
<td data-replace="code"><?=$r->code?></td>
<td data-replace="country"><?=$r->country?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<center>
<button data-next="10">Next</button>
<button data-prev="0">Prev</button>
</center>
<script src="jquery.js"></script>
<script>
$(()=>{
document.querySelector('[data-next]').addEventListener('click',function(){
move(this.dataset.next);
console.log(this.dataset.next);
this.setAttribute('data-next',parseInt(this.dataset.next) + 10);//add to next
var prv = document.querySelector('[data-prev]');
prv.setAttribute('data-prev',parseInt(prv.dataset.prev) + 10);//add to prev
})
document.querySelector('[data-prev]').addEventListener('click',function(){
move(this.dataset.prev);
console.log(this.dataset.prev);
this.setAttribute('data-prev',parseInt(this.dataset.prev) - 10);// remove form next
var nxt = document.querySelector('[data-next]');
nxt.setAttribute('data-next',parseInt(nxt.dataset.next) - 10);//remove from prev
})
function move(int){
var template = document.querySelector('tbody tr').cloneNode(true);//get a sample from tbody
$.get('table.php?ajax=true&offset='+int).success(function(data){
$(document.querySelector('tbody')).empty();
$.each(data,function(i,v){
let tp = tmp.cloneNode(true);//clone the template
tp.querySelector("[data-replace='code']").innerHTML = v.code;//replace code
tp.querySelector("[data-replace='country']").innerHTML = v.country;//replace country
document.querySelector('tbody').appendChild(tp);//append to tbody
})
});
}
});
</script>
Related
I am confused when will display product comparison table. I have 2 tables t_product_item and t_product_specification. Here's a picture of the table structure:
I want to display a product comparison like this picture :
Script:
<table border="1">
<tr style="background-color: #C3C3C3">
<td>Product</td>
<td>Spec Name</td>
<td>Spec Value</td>
</tr>
<?php
$sql = mysqli_query($conn, "SELECT item, spec_name, spec_value FROM t_product_item JOIN t_product_specification USING (item_id)");
if (mysqli_num_rows($sql)>0){
while ($row=mysqli_fetch_array($sql)){
?>
<tr>
<td><?php echo $row['item']?>
<td><?php echo $row['spec_name']?>
<td><?php echo $row['spec_value']?>
</tr>
<?php
}}
?>
</table>
Instead it appears like this
Result:
How do I structure logically or query for the table to display like the example pic?
Change your SQL Query to:
SELECT spec_name,MAX(CASE WHEN ItemId=1 THEN spec_value END)`Samsung Galaxy S8+`
,MAX(CASE WHEN ItemId=2 THEN spec_value END)`Samsung Galaxy S8`
FROM t_product_item JOIN t_product_specification USING (item_id)
GROUP BY spec_name
ORDER BY MIN(spec_Id)
Hope this helps you.
You are looping through item_id for each of your <tr> rows. Instead you should be looping through spec_name for <tr>, and for each cell <td> loop through the product.
In pseudo code:
<table>
<thead>
<tr>
<th> </th> <!-- Empty cell for spacer -->
for (item in item_list) {
<th>item.name</th>
}
</tr>
</thead>
<tbody>
<tr>
for (spec in spec_list) {
<td>spec.name</td>
}
for (item in item_list) {
<td>item.spec[spec.name]</td> <!-- display spec detail of each item -->
}
</tr>
</tbody>
</table>
You might have to restructure your data before looping it through the table.
I'm manipulating cookie data for Scheduling Calendar.
I've array in cookie, using it i have made table. Now i want to delete table rows from last delete button of last column of the row.
My Code as given below
$cookie_data = '2017-06-27+06:00-06:30,2017-06-29+12:00-12:30,2017-07-01+06:00-12:00-17:00 ';
echo '<table class="table table-bordered" id="schedule">
<tr>
<th>Date</th>
<th>Times</th>
<th>Delete</th>
</tr>';
$val = $cookie_data;
$num_dates = explode(',',$val);
foreach($num_dates as $k => $v){
$bdata = explode('+',$v);
echo '<tr><td><label>'.$bdata[0].'</label></td><td><label>'.$bdata[1].'</label></td><td><button>Delete</button></td></tr>';
}
echo '</table>';
Also Code is running on phpfiddle.
http://phpfiddle.org/main/code/8ch0-merp
Now i want to remove any value by clicking delete button.
try with this,
Currently it will give error in fiddle. because stackoverflow not allowing to set custom cookie. So you can try this code at your side, and also i convert code in html so you have to convert in php.
You can set your cookie name as you want i just give example here.
Hope this will helps you :)
$("button").on("click",function() {
var cookieStr = $(this).attr("data-cookie");
var setCookieVal = [];
var cookieValue = $("#cookievalue").val().split(",");
for(i = 0; i< cookieValue.length; i++) {
if(cookieStr !== cookieValue[i]) {
setCookieVal.push(cookieValue[i]);
}
}
$.cookie("yourCookie",setCookieVal);
$(this).parent().parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<body>
<input type="hidden" value="2017-06-27+06:00-06:30,2017-06-29+12:00-12:30,2017-07-01+06:00-12:00-17:00" id="cookievalue">
<table class="table table-bordered" id="schedule">
<tbody>
<tr>
<th>Date</th>
<th>Times</th>
<th>Delete</th>
</tr>
<tr>
<td><label>2017-06-27</label></td>
<td><label>06:00-06:30</label></td>
<td>
<button data-cookie="2017-06-27+06:00-06:30">Delete</button>
</td>
</tr>
<tr>
<td><label>2017-06-29</label></td>
<td><label>12:00-12:30</label></td>
<td>
<button data-cookie="2017-06-29+12:00-12:30">Delete</button>
</td>
</tr>
<tr>
<td><label>2017-07-01</label></td>
<td><label>06:00-12:00-17:00 </label></td>
<td>
<button data-cookie="2017-07-01+06:00-12:00-17:00">Delete</button>
</td>
</tr>
</tbody>
</table>
</body>
If do you want to delete cookie use $.dough in Jquery Plugin and for this you should specify name of the cookie like this example :
Create Cookie
//Code Starts
$.dough("cookieName", "cookieValue");
//Code Ends
Read Cookie
//Code Starts
$.dough("cookieName");
//Code Ends
Delete Cookie
//Code Starts
$.dough("cookieName", "remove");
//Code Ends
This is my form :
<div class="mutiple-array-form">
<?php $form = ActiveForm::begin(); ?>
<table id="sampleTbl", class="table table-striped table-bordered">
<thead>
<tr id="myRow">
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>william</td>
<td>32</td>
</tr>
<tr>
<td>Muli</td>
<td>25</td>
</tr>
<tr>
<td>Sukoco</td>
<td>29</td>
</tr>
</tbody>
</table>
<div class="form-group">
<?= Html::button('Create',['class' => 'btn btn-success _addNew', 'onclick' => 'myfunction()']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Below is my Javascript code :
<?php
$script = <<< JS
function myfunction() {
alert(document.getElementById("sampleTbl").rows.namedItem("myRow").innerHTML);
}
JS;
$this->registerJs($script);
?>
My code does not work. When I click button, nothing happens. For example, I want to show table value using array in alert. Please help!
What you are trying won't work because somehow declaring the function in inline script in yii2 doesnt work,i dont know proper reason of it and i am trying to find the reason.
Now your code will work if you write your script like this
<?php
$script = <<< JS
$('#idOfButton').click(function(){
alert(document.getElementById("sampleTbl").rows.namedItem("myRow").innerHTML);
});
JS;
$this->registerJs($script);
?>
And it will only print the value of your header
Now if you want the data of the table inside as an array and alert it, try this code
<?php
$script = <<< JS
$('#idOfButton').click(function(){
var myTableArray = [];
$("table#sampleTbl tr").each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).text());
});
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
});
JS;
$this->registerJs($script);
?>
And i would suggest that you use AppBundle to use script that way you will be able to debug the code via browser and figure out the problem yourself,which will help you find the answer.
PS. I know there are abundant answers for this but they seemed so complex and I'm just a beginner in codeigniter and jquery with semantic UI so I'm having difficulty in web development.
I want to know how you can implement pagination in my code from the page which is loaded with an ajax function. I find it very difficult combining ajax with codeigniter and im not a very skilled programmer so please help me on this.
The java script which it loads all the data
function viewhardware(){
$.ajax({
type: "GET",
url: "gethw",
async: true,
}).done(function( data ) {
$('#hardware').html(data);
});
}
The Controller function
public function gethw(){
$this->load->model('asset_model');
$this->data['hwares'] = $this->asset_model->get_allhw();
$this->load->view('gethware',$this->data);
}
My Model function
public function get_allhw(){
$this->db->select('*');
$this->db->from('hardware h');
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result_array();
}
else
{
return false;
}
}
and the VIEW
<table class="ui compact table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Description</th>
<th>Date Installed</th>
<th>Serial No.</th>
<th>PC ID</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<center><i class="huge desktop icon""></i><h3>Hardwares</h3>
<hr>
<?php
if(!empty($hwares)){
foreach($hwares as $hwares){
$hw_id = $hwares['hw_id'];
$hw_name = $hwares['hw_name'];
$hw_description = $hwares['hw_description'];
$hw_dateinstalled = $hwares['hw_dateinstalled'];
$hw_serialno = $hwares['hw_serialno'];
$hw_comp_id = $hwares['hw_comp_id'];
$hw_status = $hwares['hw_status'];
?>
<tr>
<th>
<?php echo $hw_id; ?>
</th>
<th>
<?php echo $hw_name; ?>
</th>
<th>
<?php echo $hw_description; ?>
</th>
<th>
<?php echo $hw_dateinstalled; ?>
</th>
<th>
<?php echo $hw_serialno; ?>
</th>
<th>
<?php echo $hw_comp_id;?>
</th>
<th>
<button class="ui basic button">
<center><i class=" <?php if($hw_status==1){ echo 'green';}else{ echo 'red'; }; ?>
desktop icon"></i>
</button>
</th>
<th><a id="editpc" class="ui button mini yellow"><i class="write icon"></i></a>
<a class="ui mini red button" href="#"><i class="remove icon"></i></a></th>
</tr>
<?php
}
}
?>
</tbody>
</table>
You can use Ajax_pagination library.
Here you will find example of how to use it.
Your controller should looks like:
function __construct() {
parent::__construct();
$this->load->library('Ajax_pagination');
$this->perPage = 1;
}
public function gethw(){
$this->load->model('asset_model');
//total rows count
$totalRec = count($this->asset_model->getRows());
//pagination configuration
$config['first_link'] = 'First';
$config['div'] = 'div-to-refresh'; //parent div tag id
$config['base_url'] = base_url().'controller/ajaxPaginationData';
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->perPage;
$this->ajax_pagination->initialize($config);
//get the posts data
$this->data['hwares'] = $this->asset_model->getRows(array('limit'=>$this->perPage));
$this->load->view('view1',$this->data);
}
function ajaxPaginationData()
{
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
//total rows count
$totalRec = count($this->asset_model->getRows());
//pagination configuration
$config['first_link'] = 'First';
$config['div'] = 'div-to-refresh'; //parent div tag id
$config['base_url'] = base_url().'controller/ajaxPaginationData';
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->perPage;
$this->ajax_pagination->initialize($config);
//get the posts data
$this->data['hwares'] = $this->asset_model->getRows(array('start'=>$offset,'limit'=>$this->perPage));
//load the view
$this->load->view('view2', $this->data, false);
}
You have to split your view in 2 parts
VIEW1
<div id="hardware">
<div id="div-to-refresh">
<?php $this->load->view('view2',$this->data); ?>
</div>
<div id="pagination"><?php echo $this->ajax_pagination->create_links(); ?></div>
</div>
view2
<table class="ui compact table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Description</th>
<th>Date Installed</th>
<th>Serial No.</th>
<th>PC ID</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<center><i class="huge desktop icon""></i><h3>Hardwares</h3>
<hr>
<?php
if(!empty($hwares)){
foreach($hwares as $hwares){
$hw_id = $hwares['hw_id'];
$hw_name = $hwares['hw_name'];
$hw_description = $hwares['hw_description'];
$hw_dateinstalled = $hwares['hw_dateinstalled'];
$hw_serialno = $hwares['hw_serialno'];
$hw_comp_id = $hwares['hw_comp_id'];
$hw_status = $hwares['hw_status'];
?>
<tr>
<th>
<?php echo $hw_id; ?>
</th>
<th>
<?php echo $hw_name; ?>
</th>
<th>
<?php echo $hw_description; ?>
</th>
<th>
<?php echo $hw_dateinstalled; ?>
</th>
<th>
<?php echo $hw_serialno; ?>
</th>
<th>
<?php echo $hw_comp_id;?>
</th>
<th>
<button class="ui basic button">
<center><i class=" <?php if($hw_status==1){ echo 'green';}else{ echo 'red'; }; ?>
desktop icon"></i>
</button>
</th>
<th><a id="editpc" class="ui button mini yellow"><i class="write icon"></i></a>
<a class="ui mini red button" href="#"><i class="remove icon"></i></a></th>
</tr>
<?php
}
}
?>
</tbody>
</table>
I can not write all code for you but this can help you.
Make changes in your model to match with this.
I'm having a problem here where I could not run DataTables.net javascripts on Joomla 1.5. The script is as what it is on DataTables
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready( function () {
var table = $('#example').DataTable();
} );
</script>
To say that it is Joomla stripping off my code, I managed to run Google Chart API javascript without any problems. Any experts here mind sharing why this is happening?
UPDATED:
Below is my code :
<?php
$doc = JFactory::getDocument();
$doc->addScript('http://code.jquery.com/jquery-1.11.0.min.js');
$doc->addScript('http://datatables.net/download/build/nightly/jquery.dataTables.js');
$doc->addScriptDeclaration('
$(document).ready( function () {
$("#example").DataTable();
});
');
function listProcess($process,$date_sort)
{
$asas= new class_asas;
$sql = "
Select proses_pendaftaran.*, secretary.*,
kpps_agih.name as kpps_agih_name,
kpps_sokong.name as kpps_sokong_name,
ppps.name as ppps_name,
tps.name as tps_name,
pjs.name as pjs_name,
pt.name as pt_name
From proses_pendaftaran
Left join jos_users secretary On secretary.id=proses_pendaftaran.user_id
Left join jos_users kpps_agih On kpps_agih.id=proses_pendaftaran.kpps_agih_id
Left join jos_users kpps_sokong On kpps_sokong.id=proses_pendaftaran.kpps_sokong_id
Left join jos_users ppps On ppps.id=proses_pendaftaran.ppps_semak_id
Left join jos_users tps On tps.id=proses_pendaftaran.tps_perakui_id
Left join jos_users pjs On pjs.id=proses_pendaftaran.pjs_lulus_id
Left join jos_users pt On ppps.id=proses_pendaftaran.pt_rekod_id
Where current_process='$process'
Order By $date_sort DESC";
//echo $sql;
return $asas->readAll($sql);
}
$userm = $asas->getUser();
$userid = $user->get('id');
$userm=$asas->getOtherUser($userid);
$usergroup = $userm['user_group_id'];
//---------------------------------------------------------------------------------------------------------------
//PJS, TPS, KPPS
if($usergroup ==7 or $usergroup ==2 or $usergroup ==3 or $usergroup ==4 or $usergroup ==5)
{
$datas=listProcess('ppps_semak','kpps_agih_date');
?>
<h1 class="contentheading">Senarai Permohonan Yang Telah Diagihkan (Menunggu Tindakan PPPS/PPPS(P))</h1>
<table id ="example" width="100%" class="systemTable">
<thead>
<tr>
<th width="20%">NAMA BADAN SUKAN</th>
<th width="10%">NAMA PEMOHON</th>
<th width="10%">TARIKH PERMOHONAN</th>
<th width="10%">PEGAWAI KPPS</th>
<th width="15%">TARIKH DIAGIHKAN</th>
<th width="10%">PEGAWAI PPPS</th>
<th width="10%">STATUS</th>
</tr>
</thead>
<?php
foreach($datas as $data)
{
?>
<tr>
<td><?php echo strtoupper($data['NamaBadan']) ?></td>
<td><?php echo strtoupper($data['name']) ?><br/>[<?php echo $data['TelPejabat'] ?>]</td>
<td><?php echo date('d/m/Y',strtotime($data['tarikh_mohon'])) ?></td>
<td><?php echo strtoupper($data['kpps_agih_name']) ?></t>
<td><?php echo date('d/m/Y (h:ia)',strtotime($data['kpps_agih_date'])) ?></td>
<td><?php echo strtoupper($data['ppps_name']) ?></t>
<td><?php echo strtoupper($data['current_process']) ?></t>
</tr>
<?php
}
?>
</table>
<br/>
<?php
}
?>
Try using the following to import the scripts and add your custom code:
$doc = JFactory::getDocument();
$doc->addScript('http://code.jquery.com/jquery-1.11.0.min.js');
$doc->addScript('http://datatables.net/download/build/nightly/jquery.dataTables.js');
$doc->addScriptDeclaration('
$(document).ready( function () {
$("#example").DataTable();
});
');
HTML:
<table id="example">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>etc</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>etc</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>etc</td>
</tr>
</tbody>
</table>
I have tested this myself a couple of minutes ago and it works perfectly for me. Please copy and paste the script (a few changes made) and HTML I have provided.
First of all, since you are in a Joomla environment there will a conflict between mootools and jquery, so you cannot use
$(document).ready( function () { $("#example").DataTable(); });
but instead
jQuery.noConflict();
jQuery(document).ready( function () { jQuery("#example").DataTable(); });
in other words, you cannot use $ when mootools library is present.
You may also consider using Tabulizer for Joomla (http://www.tabulizer.com) that has all the datatables functionality without the hassle.