Datatable: update table in realtime with animation - php

I am trying to implement functionality where it updates data in real time of my datatable with animation just like facebook ticker (last friends activities on the sidebar) but no solution found !
model file :Topic.php
public function getTopics()
{
return $this->db->select('SELECT * FROM topics');
}
index file:
<table id="example" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Sujet</th>
<th>Pièce jointe</th>
<th>Coordonnées</th>
</tr>
</thead>
<tbody>
<!--content table -->
<?php
if($data['topics']){
foreach($data['topics'] as $row){
echo '<tr>';
echo '<td>'.$row->id.'</td>';
echo '<td>'.$row->subject.'</td>';
echo '<td>'.$row->document.'</td>';
echo '<td>'.$row->x.','.$row->y.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
controller:
$data['topics'] = $this->_topic->getTopics();
$data['js'] = "<script>
$(document).ready(
function ()
{
$('#example').DataTable().ajax.reload();;
}
);
</script>";
View::renderTemplate('header');
View::render('account/topics', $data);
View::renderTemplate('footer', $data);

This is called real time functionality! There are a few days to do it!
Use ajax to update data and setInterval on the ajax function for maybe like 5s or 10s whatever you like.
The other way that I'd do is by using getting an API Pusher. Pusher is a real time functionality web app! It can be used to achieve real time functionality on your site!

You can use setInterval() to check for topics every x seconds, minutes etc:
setInterval(function(){
$.ajax({
type: 'GET',
url: 'path/to/query',
success:function(data){
if(data != ""){
$('#datatable-table').dataTable()._fnAjaxUpdate();//reloads table, syntax will differ based on datatables version
}
}
})
}, 5000);//every 5 seconds
This is only an example. You'll need to plan (for example, what happens when the response takes longer than 5 seconds?)

Related

php - How can I create dynamic urls for my language dictionary entries

I am a new learner in web development and have a language dictionary that works fine. However, I want to be able to create dynamic urls for SEO or search engine issues. For the last two days, I have been trying various approaches, including those given in stackoverflow.com, to adapt my existing codes, but unfortunately no success until now.
Well, I have two files: dictionary.php and gb-tr.php.
In dictionary.php, I have the following code block to start the query:
$('#gsearchsimple').bind("input", function() {
var query = $('#gsearchsimple').val();
if (query.length > 3) {
$.ajax({
url:"gb-tr.php",
method:"POST",
data:{query:query},
success:function(data)
{$('.list-group').html(data);}
}); } });
The query posted to the gb-tr.php file is handled with the following code block in gb-tr.php:
if(isset($_POST['query']))
{
$query = "
SELECT DISTINCT Turkish FROM gbtr
WHERE Turkish LIKE '%".trim($_POST["query"])."%'
ORDER BY length(Turkish) asc
LIMIT 20
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<li class="list-group-item contsearch">
'.$row["Turkish"].'
</li>
';
}
echo $output;
}
Then, dictionary.php shows the list generated by the above code, and when I click on one entry from the list with the following code block in dictionary.php:
$(document).on('click', '.gsearch', function(){
var edata = $(this).text();
$('#gsearchsimple').val(edata);
$('.list-group').css('display', 'none');
$("html, body").animate({ scrollTop: 0 }, 200);
$.ajax({
url:"gb-tr.php",
method:"POST",
data:{edata:edata},
success:function(data)
{
$('#detail').html(data);
}
}); });
the clicked entry is handled in gb-tr.php with the following code block:
if(isset($_POST['edata']))
{
$query = "
SELECT * FROM gbtr
WHERE English = '".trim($_POST["edata"])."' or Turkish = '".trim($_POST["edata"])."'
LIMIT 5
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
echo '
<table id="hide-table" class="table table-bordered table-striped">
<tr>
<th class="table-font-800" width="50%">English</th>
<th class="table-font-800" width="50%">Turkish</th>
</tr>
</table>';
foreach($result as $row) {
echo '<table id="hide-table" class="table table-bordered table-striped">
<tr>';
echo '<th class="table-font-100" width="50%">'.$row["English"].'</th>';
echo '<th class="table-font-100" width="50%">'.$row["Turkish"].'</th>';
echo '</tr>';
echo '</table>';
}
}
and I get the result in the dictionary.php page in the following div container:
<div id="detail" style="margin-top:16px; -webkit-hyphens: auto; -ms-hyphens: auto; hyphens: auto;"></div>
So far, I don't have any problem and everything works fine.
But for dynamic url generation, I have tried to modify the following code in gb-tr.php
foreach($result as $row)
{
$output .= '
<li class="list-group-item contsearch">
'.$row["Turkish"].'
</li>
';
}
as
'.$row["Turkish"].'
Now I can see the generated link with the variables when I hover on the relevant entry. But once I click it I get the result for a moment and then it goes away and land at the starting page with the generated url.
Can someone help me please solve my problem. I thank you in advance for reading my question.
You need to prevent the default action, of following the link, when you handle a click on a link with Javascript. In your code that would look like this:
$(document).on('click', '.gsearch', function(event) {
event.preventDefault();
<... other stuff ...>
});
See: Event.preventDefault();
Of course you would now also have to think of the case where Javascript is disabled and you actually have to react to the link that was clicked. Remember that search engines will follow your link and expect sensible results.

How to ajaxify a PHP function that does SQL in the backend?

I have broken down my problem to provide a concise example with no overhead.
Yet enough to give you an idea.
I have a simple index.php
<?php
include 'myClass.php';
?>
<html>
<head></head>
<body>
<div> <?php myClass->printTable(); ?> </div>
</body>
</html>
The function returns an entire table filled with data that is being prepared in the backend.
<?php
function printTable()
{
// printing static table header
echo ' <table class="table" style="zoom: 0.75;">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th> // current date
<th scope="col">Order Number</th> // an int
<th scope="col">Current Value</th> // an int
</tr>
</thead>
<tbody>
';
$result = mysqli_query($this->link, "SELECT * FROM `someData`");
while ($row = mysqli_fetch_assoc($result))
{
$orderNumber = $row['orderNumber'];
$currentValue = $row['currentValue'];
$date = $this->getDate($orderNumber); // member function that returns a timestamp from the database
//printing actual table
echo ' <tr>
<td>'. $date .'</td>
<td>'. $orderNumber .'</td>
<td>'. $currentValue .'</td>
</tr>
';
}
echo ' </tbody>
</table>
';
}
?>
The data I'm querying from my database is constantly changing. I want a "live" view on the frontend. I know this is done by using Ajax. But I don't understand how to do it. I looked up different resources, although none of them were actually specific enough in this approach.
On a high level: You need a PHP file ("endpoint", e.g. 'localhost/data.php') returning only the HTML code from printTable. You then use JavaScript (e.g. jQuery - $.ajax, you can lookup how it works in detail) to fetch the contents of this page each n seconds and insert into your page.
I was looking for broad or unspecific way to get some data from the backend and display it within a div on my page.
The solution was to create a separate PHP (fetch.php) file that echoes only the data I need to display within my div
from my page which contains my div I'd do the following:
<div id="result"></div>
<script>
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data()
</script>
Inside fetch.php I can do whatever I want, including querying my database and store the values in a variable which will be echoed at the end. This response (echo) from fetch.php will then be displayed inside my div.
Similarly, I could also specify a .txt inside the ajax function (url:"sometext.txt")
The contents of the .txt could also be displayed inside my div this way. My lack of understanding of how this works made it really difficult to understand.
Additionally, I have added a function to refresh the contents (or response) every second.
If I would echo time() from fetch.php it would automatically increment without page reload inside my div
setInterval(function(){
load_data()
}, 1000);

I need a script to change a link when clicked on it to another content

i am working on student supervision project. i wanted to create a page that contain the available project topics, when clicked on a topic of interest, to assigns the topic to the user with that 'id' and renders the link unavailable e.g a topic that has a link 'available' to change to 'unavailable'.
i will really apreciate if someone in the house can help?
Thanks
You need to use ajax for it, that way and helping with jquery you make the changes in real time
I made some small changes to perform this action with jquery
<body>
<table cellspacing="2" cellpadding="2" border="2">
<?php $sql = "Select * from prject_topic"; $result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['lecturer_name'];?></td>
<td><?php echo $row['topic'];?></td>
<td><span class="actu" id="<?php echo $row['project_id'];?>">
<?php echo $row['status'];?>
</span>
</td>
</tr> <?php } ?>
</table>
<script type="text/javascript">
$(function(){
//We capture the Click in the user item
$(".actu").on('click', function(){
//We take the ide of this item
var id = $(this).attr('id');
//We check the current status of the user
if($(this).html() == "Deactivate"){
var est = "Activate";
}else{
var est = "Deactivate";
}
//We made a request of type ajax sending by post the id for its update
$.post('#.php',
{
'id':id,
'est':est
},
//We received the response from our php file which may be a code as in the example...
function(data){
if(data=="200"){
//If yes, update the content of the selected item in real time
$("#"+id).html('Deactivate');
}else{
//In case of error, we send the information
alert("Unable to disable user");
}
})
})
})
</script>
</body>
The code is written for your understanding

Why I am having problems with my output using html/jquery/php

Problem no 1 Why my table do not align?
Problem no 2 Why everytime I click my Warrior List at the nav the output goes like this
Here's my js
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
success: function(data) {
$('#listWarriors').append(data);
}
});
}
Here's my html
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</table>
</article>
And heres my php
foreach($result as $names){
$warriors['wname'] = $names['warrior_name'];
$warriors['wtype'] = $names['warrior_type'];
echo '<tr>
<td>'.$warriors['wname'].'</td>
<td>'.$warriors['wtype'].'</td>
</tr>';
}
the result is appended under the </table>
try change your ajax success to :
$('#listWarriors table').append(data);
for number2, im affraid it's truncated by the container (#listWarriors)..
check your css of that id if the width is fixed or not...make it wider as you please
The way you have your jQuery, you are appending the content to the '' tag, and not to the table.
This is what happens when each item is appended, with the way its setup (I added a thead tag by the way. Will come in handy once you start styling your table)
This is the output when things are appended, and why its rendering wrong.
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<thead>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</thead>
</table>
<tr>
<td>the wname</td>
<td>the wtype</td>
</tr>
</article>
With that said modify your jquery to
$('#listWarriors table').append(data);
By the way,
How many items are you wanting to append. If you will make multiple ajax calls and append things one at a time, I would recommend getting the data through JSON. Let me know, if I can help
AS DISCUSSED IN COMMENTS SINCE YOU WANT TO GET MULTIPLE ITEMS JSON IS THE WAY TO GO. You can pass data using JSON this way
**The php (Im sure you already have the query already done but here it is just in case) **
// Make a MySQL Connection
$query = "SELECT * FROM example";//Your query to get warriors from db
$result = mysql_query($query) or die(mysql_error());
$myWarriorsArray = array();//Where you will store your warriors
while($row = mysql_fetch_array($result)){
$myWarriorsArray[] = $row;
//This stores all keys for each iteration
/*//This is teh same as the following commented code
$myWarriorArray['warrior_name'] = row['warrior_name'];
$myWarriorArray['warrior_type'] = row['warrior_type'];
*/
}
echo json_encode($myWarriorsArray);//This will return a json object to your ajax call
The Javascript
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
dataType : 'json',
success: function(data) {
var toAppend = '';
alert(data);
//console.log(data);//Uncomment this to see the returned json data in browser console
for(var i=0;i<data.length;i++){//Loop through each warrior
var warrior = data[i];
toAppend += '<tr>';
toAppend += '<td>'+data[i]['warrior_name']+'</td>';
toAppend += '<td>'+data[i]['warrior_type']+'</td>';
toAppend += '</tr>';
}
$('#listWarriors table').append(toAppend);
}
});
}

Obtaining ROW ID from a Table created with MySql to use with an OnClick Function

I have a table created with PHP from an Sql Database that successfully displays the table information
using the following code example.
<table class="mytable loottable" id="guildmembers">
<?php
$query = mysql_query("SELECT $member.charname, $member.char_lvl, $trskill.skill_desc, .....
if (mysql_num_rows($query) > 0) {
while (false !== ($row = mysql_fetch_assoc($query))) {
echo '<tr id="'.$row['charname'].'">'; <-- setting row id here
echo '<td class="lootrow" id="memth1">'.$row['charname'].'</td>';
echo '<td class="lootrow" id="memth2">'.$row['rank_desc'].'</td>';
echo '<td class="lootrow" id="memth3">'.$row['class_name'].'</td>';
echo '<td class="lootrow" id="memth4">'.$row['char_lvl'].'</td>';
echo"</tr>\n";
}
mysql_free_result($query);
}
?>
</table>
Example of page source where i have verified that each table row is assigned the correct id.
<tr id="Calysta"><td class="lootrow" id="memth1">Calysta</td><td class="lootrow" id="memth2">Guild Leader</td><td class="lootrow" id="memth3">Inquisitor</td></tr>
<tr id="Rynanx"><td class="lootrow" id="memth1">Rynanx</td><td class="lootrow" id="memth2">Guild Leader</td><td class="lootrow" id="memth3">Mystic</td>
I am setting each table ROW ID to the first field which is always unique. Then i am trying to use this
ID in the following function to redirect users to a profile page when they click on a row in the table.
<script type="text/javascript">
$(document).ready(function () {
$("table.mytable").each( function() {
table = $(this);
if ($(table).attr("id")=="guildmembers") {
$(this).click(function(){
window.location.href = "http://eq2players.com"+
"/Kithicor/" + $(this).attr("id") + "/";
});
}
})
});
</script>
Which should open a new page in the browser with the following address for instance if the
first row is clicked : "http://everquest2.com/Kithicor/Calysta/"
Instead no matter which row is clicked the web url being created
is "http://everquest2.com/Kithicor/guildmembers/"
which is the Tables ID. not the ID of the row being clicked. I have tried various solutions
and cannot figure how to get the row ID in this click function. Any help with this would
much appreciated. Thanks.
Here you go, just did this quick, changed some things, please be mindful of using duplicate id's its BAD, you shouldn't. Also you over complicated your Javascript:
HTML EXAMPLE:
<table class="mytable loottable" id="guildmembers">
<tr class="linkRow" id="test1">
<td>test1</td>
</tr>
<tr class="linkRow" id="test2">
<td>test2</td>
</tr>
<tr class="linkRow" id="test3">
<td>test3</td>
</tr>
</table>
jQuery:
$(document).ready(function () {
$(".linkRow").each( function() {
id = $(this).attr("id")
$(this).click(function(){
window.location.href = "http://eq2players.com"+
"/Kithicor/" + id + "/";
});
});
});
jsFiddle Link:
http://jsfiddle.net/TJBX5/
You are installing your click handler on the table. Therefore, when you call $(this).attr("id"), you are asking for the table's id. You need to install the click handler on each row in the table.

Categories