I have a table function (table_view.php)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test_coding_rosa/table_design2.css">
</head>
<body>
<?php
$row_id="";
if($_GET['page']==1 || isset($_GET['page'])==false){
$row_id=1;
}elseif (isset($_GET['page']) && $_GET['page']>1) {
$row_id=($_GET['page']-1)."1";
}
$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('
jQuery(document).ready( function () {
jQuery("#main-table").DataTable();
});
');
?>
<h1><?php echo $this->title ?></h1>
<table id="main-table" border="<?php echo $this->tableBorder ?>" class="display" <?php if(!empty($this->tableWidth)) echo 'width="'.$this->tableWidth.'"';?> >
<thead>
<?php
if(!$this->hideHeaderTable)
{
if($_GET['t']!='maklumat_ringkas'){
echo "<tr><th width='10px'>Bil</th>";
}
foreach($this->tableData[0] as $key=>$tableHeader)
{
?>
<th width="<?php echo $this->tableData[1][$key] ?>" scope="col"><?php echo $this->tableData[0][$key] ?></th>
<?php
}
?>
</tr>
</thead>
<?php
}
$lenData = count($this->tableData);
for ($j=3;$j < $lenData; ++$j)
{
?>
<tbody>
<tr class="centertable" <?php if($j % 2==1) echo 'bgcolor="#EFF4FB"'?>><?php if($_GET['t']!='maklumat_ringkas'){echo "<td>".$row_id++."</td>";}?>
<?php
foreach($this->tableData[0] as $key=>$tableHeader)
{
?>
<td width="<?php echo $this->tableData[1][$key] ?>" <?php echo $this->tableData[2][$key] ?>><?php echo stripslashes($this->tableData[$j][$key]) ?></td>
<?php
}
?>
</tr>
</tbody>
<?php
}
?>
</table>
</body>
</html>
This table_view.php is the default table for all data in the site. As you can see in the photo below, there are multiple tables being called from table_view.php.
The problem here is, I wanted to use DataTables.net to include the pagination of the tables. However, only the first table has been successfully implemented with DataTables.net plugin.
How can I implement it on all of the tables? Since all the tables are being called from the same function file (table_view.php), the table id is the same.
UPDATED declaration
$doc = JFactory::getDocument();
$doc->addScriptDeclaration("
jQuery('[id='main-table']').each(function(i,e) {
var id=jQuery(this).attr('id');
jQuery(this).attr('id', id+'_'+i);
jQuery(this).addClass('datatable-identifier');
}); ");
$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('
jQuery(document).ready( function () {
jQuery(".datatable-identifier").dataTable();
} );
Having multiple elements with the same id is a very bad habit :) You should really try to avoid it. Though HTML is forgiving, it results as you see in all kind of problems when trying to access elements in javascript.
If it is impossible to avoid, you could run the following function before calling dataTable() :
jQuery('[id="main-table"]').each(function(i,e) {
var id=jQuery(this).attr('id');
jQuery(this).attr('id', id+'_'+i);
jQuery(this).addClass('datatable-identifier');
});
This will rename the table id's to main-table_1, main-table_2 and so on. The class datatable-identifier is just a dummy class used when initializing the dataTables, change your code to :
jQuery(document).ready( function () {
jQuery(".datatable-identifier").dataTable();
});
Related
I'm trying to create a table, and in each row there will be a picture, and when the picture is clicked a js function gets executed, each entry of a row in the table will create a js script for the picture of that row. And for that reason I'm using <?php echo ?> on the id of the image and on the getElementById in the script. And I have no problem using the echo on the id of the image, but if I put it inside getElementById the js code doesn't get executed. And if I write instead directly the number of the id let's say
getElementById("3") instead of getElementById("<?php echo $contact['id']; ?>") it works perfectly, but if use echo it doesn't, even when the source code of the loaded page shows that getElementById("<?php echo $contact['id']; ?>") successfully got printed as getElementById("3")
Here's the full table's code:
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php $contacts = getContacts();
if($contacts->num_rows) {
foreach($contacts as $contact) { ?>
<tr>
<td>
<img id="<?php echo $contact['id']; ?>" src="img/arrow.png" onclick='removeImage("");'>
<script type="text/javascript">
function removeImage() {
document.getElementById("<?php echo $contact['id']; ?>").style.display = "none";
}
</script>
</td>
<td><?php echo $contact['Name']; ?></td>
<td><?php echo $contact['Status']; ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
When looping, you are recreating the same function over and over again, but with a different ID in each. However, you can't create the same function over and over again with the same name.
On your img change removeImage('') to removeImage(this)
<img id="<?php echo $contact['id']; ?>" src="img/arrow.png" onclick='removeImage(this);'>
Then outside of the loop just have a single function that refers to the element passed to it
function removeImage(el) {
el.style.display = "none";
}
I have a problem. I checked tons of good answers and tried them. Some helped me a lot but I still can't solve my problem completely. Can someone please help me?
I have one text file with following lines:
123456789, c
123456790, c
123456791, c
123456792, d
I read and parse this text file using a PHP script:
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
}
I can reach to the result of this php script with JS code below:
var userConStats = <?php echo json_encode( $myusers ) ?>;
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
with this; I filled the necessary html table for the first time. Everything is perfect.
The problem starts when I want this PHP to read text file every second and refresh the table elements according to the changes in the text file. PHP parse the text file only once and the changes in the text file won't change anything on the browser.
Maybe my approach to the problem was wrong I am not sure.
Any help will be appreciated. Thank you!
Complete code can be found below:
<?php
require 'connectionNetIndex2.php';
include 'txtPHP.php';
include 'userConStatUpdater.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>2-NetIndex</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>MY_TEST</h1>
<select name="OperationalMode">
<option value="">Normal</option>
<?php while($opMode = mysqli_fetch_assoc($opModes)) { ?>
<option value="<?php echo $opMode["operational_mode"]; ?>"><?php echo $opMode["operational_mode"]; ?></option>
<?php } ?>
</select>
<?php if(isset($Users)): ?>
<table>
<tr>
<td>IMSI</td>
<td>Connection Status</td>
<td>Profile</td>
</tr>
<?php foreach($Users as $user): ?>
<tr>
<td value="<?php echo $user["u_id"]; ?>"><?php echo $user["imsi"]; ?></td>
<td id="<?php echo $user['imsi'];?>" class="conStats"></td>
<td><form action="" method="POST">
<select id="profiles" name="Profiles" onchange="valueChanged()">
<option value="<?php echo $user["p_id"]; ?>"><?php echo $user["profile_name"]; ?></option>
<?php foreach($profiles as $PR): ?>
<option name="" value="<?php echo $PR["p_id"]; ?>"><?php echo $PR["profile_name"]; ?></option>
<?php endforeach; ?>
</select>
<input name="uid" type="hidden" value="<?php echo $user["u_id"]; ?>">
<!--<input type="submit" value="save">-->
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<script type="text/javascript">
function conStatUpdater(){
<?php
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
json_encode( $myusers ) ;
}
?>
// pass PHP array to JavaScript array
//Dont refresh the elements.
var userConStats = <?php echo json_encode( $myusers ) ?>;
//test is function working every second?
//test result : YES
console.log(userConStats[0][1]);
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
}
setInterval(conStatUpdater, 1000);
</script>
</body>
</html>
Like you've realized, PHP can't update an HTML page after it's been generated (unless you reload the page). You can only do that with JavaScript. In order to get the data every second, you'd need to use ajax (https://www.w3schools.com/xml/ajax_intro.asp) to make asynchronous calls every second to your PHP page to get the data. So you'd need something like this:
PHP:
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
}
print json_encode($myusers);
Your JavaScript code:
function updatePage(userConStats) {
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
}
var secondPerRequest = 1;
setInterval(function() {
$.ajax({
url: "<your php page>",
success: function(result) {
var resultAsObject = JSON.parse(result);
updatePage(resultAsObject);
}
});
}, secondsPerRequest * 1000);
Note that I used jQuery to do the ajax call because it's simpler that way. If you don't want to use jQuery, you can find info on how to do ajax in vanilla JS here: How to make an AJAX call without jQuery?
the <?php ... ?> block script inside your conStatUpdater() javascript function will not re-executed on the server-side because it is already parsed and will only yield the same result.
what you need is an AJAX function that will call your php script, in which that php script will re-executed on server-side and respond you with an updated values on your text files.
I want to add confirm box by using JavaScript. So, here is the code that I have used. When I click on the Delete button, it shows me a Confirmation message and when I click Ok, it doesn't delete my row.
What is wrong with this? How can I fix this?
Here is the Index Page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Bootstrap core CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row"> <!-- Start Of The Row Class -->
<div class="col-md-8 col-sm-4 hero-feature"> <!-- Start Of The Col Class -->
<br><br>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include('ksdb.php');
// get results from database
$result = mysql_query("SELECT * FROM academic")
or die(mysql_error());
?>
<table class='table table-bordered'>
<tr class='danger'>
<th>ID</th>
<th>Name</th>
<th>Username</th>
</tr>
<?php
// display data in table
while($row = mysql_fetch_array( $result )) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><a href="AdminChangePw.php?id=<?php echo $row['id']; ?>" alt="edit" >Change</a></td>
<td><a href="AdminEdit.php?id=<?php echo $row['id']; ?>" alt="edit" >Edit</a></td>
<td><input type="button" onClick="deleteme(<?php echo $row['id']; ?>)" name="Delete" value="Delete"></td>
</tr>
<script language="javascript">
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id=' +id+'";
return true;
}
}
</script>
<?php
}
?>
</table>
</div> <!-- End Of The Col Class -->
</div> <!-- End Of The Row Class -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></script>
</body>
</html>
Change the id to 'delid'. You are calling the function as deleteme(delid).
So You Must use delid, instead of id.
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id="+delid; /*Change id to 'delid'*/
return true;
}
}
Use
window.location.href
Instead of window.location
There are a couple of problems with your function:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id='+id+'";// this should be delid, also bad quotes, also you want to set the href, not the location
return true;
}
}
Fixed:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id=" + delid;
return true;
}
}
I have the following code for a dropbox;
<select name="Symptom" id="Symptomid" onchange="LSC()">
On change in the dropbox i want to run the following php code;
<?php
$data = array();
{
$symptoms_name = $_POST['Symptom'];
$sql1 = mysql_query("SELECT name,description , comments
FROM symptoms WHERE symptoms.name ='$symptoms_name'") or
die(mysql_error());
while($row1 = mysql_fetch_assoc($sql1)){
$data[] = $row1;
}
}
?>
<?php
if($data){
?>
<table border="1">
<tr>
<td>name</td>
<td>description</td>
<td>comments</td>
</tr>
<?php
if($data){
foreach($data as $sy){
?>
<tr>
<td><?php echo $sy['name']; ?> </td>
<td><?php echo $sy['description']; ?> </td>
<td><?php echo $sy['comments']; ?> </td>
</tr>
<?php
}
}
?>
<?php
}
?>
</table>
}
and display this table under the dropbox on the original html .
I think we have to run a java script which will call the php function and retun the table to the original html.
Kindly assist, I know we have to use ajax.
Regards
Azhar
sorted,
see this has a similar problem
http://www.w3schools.com/php/php_ajax_database.asp
Regards
Azhar
I had a home page which have a few tables that refresh itself every few sec.
Below is the code for the jquery in view file (inside_view.php)
<script>
$(document).ready(function() {
$("#encontainer").load("inside/home_en");
var refreshId = setInterval(function() {
$("#encontainer").load('inside/home_en?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="encontainer"></div>
and here is the controller code (inside.php)
function index(){
// Write to $title
$this->template->write('title', 'Update to date data');
$this->template->write_view('header', 'header_content', true);
// Write to $content
$this->template->write_view('content', 'inside_view', true);
// Write to $sidebar
$this->template->write_view('sidebar', 'user_side_menu');
// Load and display the template
$this->template->load();
}
function home_en(){
//look latest enquirer data
$data['enresults'] = $this->customer_model->get_cp_list(5);
$this->load->view('ajax_home_en',$data);
}
here is the (ajax_home_en.php) code
<link type="text/css" rel="stylesheet" href="http://bravonet.my/tombocrm/assets/css/table.css" />
<?php if($enresults->num_rows() == 0){
echo 'No data result, please insert one';
}else{
?>
<table width="100%">
<tr>
<th>CP code</th>
<th>Code</th>
<th>Name</th>
</tr>
<?php foreach($enresults->result() as $row){
echo '<tr class="tr'. alternator('1', '2'). '">';
?>
<td align="center"><?php echo $row->cp_code?></td>
<td align="center"><?php echo $row->en_code?></td>
<td align="center"><?php echo $row->name?></td>
<td align="center"><?php echo anchor('customers/patient_update_view/'.$row->eid,'Edit');?></td>
<td align="center"><?php echo anchor('customers/cp_details_view/'.$row->cpid,'View');?></td>
</tr>
<?php }?>
</table>
<?php
echo anchor('customers','View all data');
} ?>
Everything is fine when i try to view this page with this url
http://mysite.com/inside
but once i type this url
http://mysite.com/inside/ or this http://mysite.com/inside/index
the
<div id="encontainer"></div>
show inside() view instead of home_en() view. n will have continuous page refreshing in the box (and makes my IE stop responding).
I don't understand why adding a "/" or /index in the URL will cause such bug, is my javascript appear error?
thx in advanced!
It might be an issue with relative links, try:
$(function() {
$("#encontainer").load("/inside/home_en");
var refreshId = setInterval(function() {
$("#encontainer").load('/inside/home_en?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});