Auto refresh of online users table without refreshing whole page - javascript

I have a table displaying the list of online and offline users in my dashboard page. I'm trying to automatically refresh the entire table every 5 seconds to show if there are other users who just logged in or out without refreshing the whole page. I have searched through different threads and pages regarding this which is telling me to use AJAX or JSP. But I can't seem to make it work.
This is my table:
<div class="col-md-2">
<table class="table table-striped">
<thead>
<tr>
<th>Status</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php
$online = DB::table('users')->where('group_id', $user->group_id)->orderBy('online', 'desc')->get();
foreach($online as $val=>$key)
{ ?>
<tr>
<td><?php if ($key->online == 1) { echo '<span class="label label-success">Online</span>'; } else { echo '<span class="label label-warning">Offline</span>'; } ?></td>
<td><?=$key->first_name." ".$key->last_name?></td>
</tr>
<?php } ?>
</tbody>
</table>
I found this code on a different thread, but when I tried to use it on my project, it wasn't loading the data in my table. I'm not very familiar working with javascripts or AJAX, so I'm hoping you can help me out. It'll be very much appreciated.
<script>
$(document).ready(function(){
$("#refresh").click(function()
{
$("#Container").load("content-that-needs-to-refresh.php");
return false;
});
});
</script>
<div id="Container">
<?php include('content-that-needs-to-refresh.php'); ?>
</div>
Refresh

In your case perfectly working for you.
setInterval(function()
{
//call ajax here..for your table result
}
}, 3000);
and then ajax will giving you result every 3 second.
I hope it will work for you.

Make sure you loaded jQuery. You can use Google CDN or save it and load it on your own server.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Use setInterval
<script>
$(document).ready(function(){
var refreshUsers = setInterval(function() {
$("#Container").load("content-that-needs-to-refresh.php");
}, 5000); // 5000 ms = 5 sec
});
</script>
<div id="Container">
<?php include('content-that-needs-to-refresh.php'); ?>
</div>
If you should want to stop refreshing, use
clearInterval(refreshUsers);

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

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

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

how to get array of table after click button in YII2

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.

sending jQuery sortable data via ajax

I am working with jQuery Sortable and twitter bootstrap as well. I have table rows that I am trying to sort. The drag and drop is working fine but I am trying to send the new sort order via ajax which is not picking up/sending the sort order and when i try to alert the data it seems empty.
This is my PHP code which is using loop to pull the records from MySQL
<table class="table table-striped table-bordered ">
<thead>
<tr>
<th> Slide Title</th>
<th> Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<tr id="<?php echo $row['id']; ?>">
<td>
<?php echo $row['title']; ?>
</td>
<td>
<div class="btn-group pull-right">
<button data-toggle="dropdown" class="btn btn-small btn-info dropdown-toggle">
Action<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li>Edit
</li>
<li>
Delete
</li>
</ul>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
and this is the java script that is doing the sorting and then sending data to a file called slides.php
$(document).ready(function(){
$(function() {
$('table').sortable({
items: 'tr',
opacity: 0.6,
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data);
$.ajax({
data: data,
type: 'POST',
url: 'slides.php'
});
}
});
});
});
What I feel is my variable data var data = $(this).sortable('serialize'); is not working, if i send a static variable then I am able to see that in $_POST
I will really really appreciate any assistance in this.
I ended up following up the concept mentioned on this link to do my task, for some reason current solution was not working with <table> so I just re wrote the html part using <ul></ul> and it worked.
I hope this helps anyone out there having the same problem.

Categories

Resources