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.
Related
I am trying to display my images in a for loop in the form tag using PHP but it does not seem to work. I have also tried doing a return statement but nothing still appears.
<?php
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
function displayCheckboxes(){
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i] . "<br>";
}
}
?>
<body>
<main id ="main">
<form id="pics" action="process.php" method="get">
<label>Name: </label>
<?php echo displayCheckboxes();?>
</form>
</main>
</body>
Maybe Like This:
<?php
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
function displayCheckboxes(){
global $data;
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i]."'>" . "<br>";
}
}
displayCheckboxes();
?>
function displayCheckboxes($img_array){
foreach($img_array as $img) {
echo "<img src='".$img."'>'" . "<br>";
}
}
and
echo displayCheckboxes($data);
There is several errors with your function :
- $data is not inside the function
- .jpg is already in the image name.
this should work,call the function with $data
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
/* Write your displayCheckboxes() function here */
displayCheckboxes($data);
function displayCheckboxes($data){
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i]."'.jpg>'" . "<br>";
}
}
?>
<?php
$data = array(
"images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg"
);
?>
<body>
<main id ="main">
<form id="pics" action="process.php" method="get">
<label>Name: </label>
<?php foreach($data as $image): ?>
<img src="<?= $image; ?>"></br>
<?php endforeach; ?>
</form>
</main>
</body>
This is an alternative way. Looks much cleaner and readable. And I actually don't think we need a function for printing HTML.
I would say NEVER put HTML inside PHP echo unless it is compulsory. The reason I am stating this is if you put HTML inside PHP, the code becomes easily messy. It becomes hard to understand the logic unless you are the one who coded. Particularly, if you are working with some designers or in future, they will have a hard time making even little changes.
Even I think using <?= than <?php echo is better.
You are trying to give an extension ".jpg" of the images that you previously gave to it in the path of images in the array "$data".
For exemple:We will take the first element in the array $data with index = 0 "$data[0]" (images/architecture-57e8d34a48_640.jpg):
In PHP looks like -> echo "<img src='".$data[0]."jpg'>" . "<br>";
,but in HTML looks like -> <img src='images/architecture-57e8d34a48_640.jpg.jpg'>
You shold have to delete the extension ".jpg" from your echo to seem like:
echo "<img src='".$data[$i]."'>" . "<br>";
I want to ask for help because I have a problem creating buttons using a for and put in the onclick the name of a function with a parameter, but this parameter is a string, I get an array and end of the cycle all buttons have the name of the last element of the array rather than each position of the array .. Thanks in advance for your help ..
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
function enviar(periodo){
alert(periodo);
}
</script>
</head>
<body>
<?php
$formatos=
array(array('idPeriodo'=>'pp2019'),
array('idPeriodo'=>'pp2018'),
array('idPeriodo'=>'pp2017'),
array('idPeriodo'=>'pp2016'));
for($l=0; $l< count($formatos); $l++){
?>
<button onclick="enviar(<?php echo json_encode($formatos[$l]['idPeriodo'])?>)">Guardar</button>
<?php
}
?>
</body>
</html>
You already have a PHP loop, so the javascript bit is useless.
Try this:
<?php
for($l=0; $l< count($formatos); $l++){
$per = json_encode($formatos[$l]['idPeriodo']);
?>
<button onclick="enviar('<?= $per ?>')">Guardar</button>
<?
}
?>
Is there any reason you want it json_encode? this works. Try this :
EDIT
<?php
$formatos=
array(array('idPeriodo'=>'pp2019'),
array('idPeriodo'=>'pp2018'),
array('idPeriodo'=>'pp2017'),
array('idPeriodo'=>'pp2016'));
for($l=0; $l< count($formatos); $l++){
$periodo = $formatos[$l]['idPeriodo'];
?>
<button onclick="enviar('<?php echo $periodo; ?>')">Guardar</button>
<?php
}
?>
You get the last element of the array because you redefine per variable every time. Use this code:
<?php
$formatos=
array(array('idPeriodo'=>'pp2019'),
array('idPeriodo'=>'pp2018'),
array('idPeriodo'=>'pp2017'),
array('idPeriodo'=>'pp2016'));
for($l=0; $l< count($formatos); $l++){
$param = json_encode($formatos[$l]['idPeriodo']);
$param = addslashes($param);
?>
<button onclick="enviar(<?php echo $param; ?>)">Guardar</button>
<?php
}
?>
Try this script and hope this will work :
<?php
$formatos = array(
array('idPeriodo'=>'pp2019'),
array('idPeriodo'=>'pp2018'),
array('idPeriodo'=>'pp2017'),
array('idPeriodo'=>'pp2016')
);
for($l = 0; $l < count($formatos); $l++) {
?>
<button onclick='enviar(<?php echo json_encode($formatos[$l]['idPeriodo']);?>)'>Guardar</button>
<?php } ?>
I have a project in which I am displaying a button tag in a while loop. On every button click I want to display an alert box with the respective UserId. Here is my code:
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
<?php } ?>
Here is my validate function:
function validate1(id2)
{
// var id2;
id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
But it is always showing me last user id .. whereas i want to display userid for every user on everyclick.
Can someone help?
Here man, the function you were calling was undefined validate1, also you don't need to get any arguments on your function declaration, since you are not passing any arguments when you invoke it.
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
JS
function validate(){
var id2 = document.getElementById('demo').getAttribute('value');
alert(id2);
}
try this in your code
HTML:
<button onClick="validate('<?php echo $RegisterId; ?>')">Show Interest</button>
Javascript:
function validate(id2)
{
alert(id2);
}
Your code needs some modifications.
Firstly, you have made a provision to send id to javascript function, but, you are not passing id to it.
PHP
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo $dis1['RegisterId'];?>">
<button onClick="validate('<?php echo $dis1['RegisterId'];?>')">Show Interest</button>
</div>
<?php } ?>
Javascript:
function validate1(id2) {
// var id2;
//id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
With this code, your clicks shouldn't even return the last id. Your javascript function is not looking good.
This should work;
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<!-- removed id attribute, as they're unique, you can't set it to every div.
If you really need id attribute, you can set one by using your RegisterId (e.g. id="demo-<?php echo $RegisterId; ?>)
And moved value attribute to button tag, it's much more useful in it. -->
<div>
<button onClick="validate(this)" value="<?php echo "$RegisterId" ?>">Show Interest</button>
</div>
<?php } ?>
Javascript
function validate(element){
alert(element.value)
}
This way, you can use it in other stuff much easier.
I'm using ajax post method for show result when select item.
now i want get the items when the page loads but my code show result only when select an item i want show result from selected item when page load my ajax post code this is:
<script type="text/javascript" >
aaa = jQuery.noConflict();
function getItems(catid){
aaa.post('articles.php',{catid: catid},function(data){
aaa('#articlediv').html(data);}
);
}
</script>
<select type="list" name="categorylist" onChange="getItems(this.value)">
<?php
foreach($categoryid as $catid){
$title = modadcatarticlesHelper::getCatById($catid);
?>
<option value="<?php echo $catid ?>"><?php echo $title ?></option>
<?php } ?>
</select>
try this,
<select type="list" name="categorylist" onChange="getItems(this.value)">
<?php
foreach($categoryid as $catid){
$title = modadcatarticlesHelper::getCatById($catid);
?>
<option value="<?php echo $catid ?>"><?php echo $title ?></option>
<?php } ?>
</select>
<script type="text/javascript" >
aaa = jQuery.noConflict();
function getItems(catid){
aaa.post('articles.php',{catid: catid},function(data){
aaa('#articlediv').html(data);}
);
}
window.onload = getItems('1');
</script>
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();
});