how to get array of table after click button in YII2 - javascript

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.

Related

Refresh table which contain a php code

I have a PHP code, which is in a table tag.It shows a text from database. I want to refresh this table, to load updated text from database in every - let's say - 1 minute without refreshing the whole page. I've found several solutions to reload table without refreshing a page and it seems it can be done with AJAX or JS, but they only refresh it with a specific content or a specific file, however, I can't figure out how to refreshed.
<table class="table table-striped">
<thead>
<tr>
<th>Department</th>
<th class="col_small col_center">Employees</th>
<th class="col_small col_center">% Percentage</th>
</tr>
</thead>
<tbody>
<?php $employeeslist=$emp_departmentObj->selectorgall();
foreach($employeeslist as $list)
{
$total=$emp_regObj->selectorgall();
$totalemp=count($total);
$deptemp=$emp_regObj->selectemployee($list->id);
$totaldeptemp=count($deptemp);
$percentage=($totaldeptemp/$totalemp)*100;
?>
<tr>
<td><?php echo $list->department ?></td>
<td class="col_center">
<?php echo $totaldeptemp; ?>
</td>
<td class="col_center">
<?php echo number_format($percentage,1).'%'; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
You can define a function in document ready like this
$(document).ready(function() {
setInterval(function() { rebindTable() }, 3000);
function rebindTable() {
$.ajax({
url: "http://localhost:80/data.php",
success: function(result) {
var data = result;
$('#td-1-data').html(data.param1);
$('#td-2-data').html(data.param2);
}
});
}
})
this way you can use an setInterval method and re-bind the data in the table using ajax , in this i assume your http://localhost:80/data.php is returning some data which your are binding to the td of the table you have defined

table pagination without reload the page -Bootstrap-

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>

Remove Specific Data from Cookie using jQuery or Javascript

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

Codeigniter run jquery function again after ajax call

How to apply jquery after Ajax Calling in codeigniter
my code of ajax calling
function load_data_ajax(type){
$.ajax({
'url' : '/index.php?compose/get_list',
'type' : 'POST', //the way you want to send data to your URL
'data' : {'type' : type.value},
'success' : function(data){ //probably this request will return anything, it'll be put in var "data"
var container = $('#container'); //jquery selector (get element by id)
if(data){
$('#container').html(data);
}
}
});
}
My Html
<table align="center">
<tr>
<td>
<font class="formpromp">Select Category: </font>
<SELECT name="crs" onchange='load_data_ajax(this)'>
<?php
foreach($query as $rowcrs):
echo "<OPTION value='".$rowcrs['CD']."'>".$rowcrs['TITLE1']."</OPTION>\n";
endforeach;
?>
</SELECT>
</td>
</tr>
</table>
<div id="container">
<table id='table1' border='1' cellspacing='0' cellpadding='0'><thead><tr>
<th align='left'><input type='checkbox' value='' />Code</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>huzefa</td>
</tr>
<tr>
<td>2</td>
<td>husain</td>
</tr>
</tbody>
</table>
</div>
I am using Table filtergrid for table
<script type="text/javascript" language="javascript" id="t3">
var tf = setFilterGrid('table1', props);
</script>
ITS properly load First time, but i cant understand how to load java script after Ajax Data load.
Please any one help me.
Thanks

Cannot add DataTables.net javascript to Joomla 1.5

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.

Categories

Resources