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 } ?>
Related
i have div with id like this
<div id='alert<?php echo $row['no']?>'>
<b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
</div>
and i need to call that id in javascript,
i try like this but the value not right
$("#alert<?php echo $row['no'] ?>").hide();
how to fix it
thankyou
You need to include jQuery CDN
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$("#alert<?php echo $row['no'] ?>").hide();
</script>
I'm assuming that you have something like this:
foreach($result as $row){
?>
<div id='alert<?php echo $row['no']?>'>
<b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
</div>
<script>$("#alert<?php echo $row['no'] ?>").hide();</script>
<?php
}
Otherwise if the script-tag is outside the loop then it wount work.
Another solution would be to make a function let say hideAlert(div)
and do something like this:
<?php
foreach($result as $row){
?>
<div onload="hideAlert(this)">
<b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
</div>
<?php
}
?>
<script>
function hideAlert(div){
div.hide();
}
</script>
if you need the id to reference to it later you could just change the code like this:
foreach($result as $row){
?>
<div onload="hideAlert(<?php echo $row['no']; ?>)">
<b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
</div>
<?php
}
?>
<script>
function hideAlert(id){
$(`#alert${id}`).hide();
}
</script>
Keep in mind that I'm not an expert on jQuery soo I'm not really sure if this works but i hope it helps :)
<?php
for($i=0;$i<5;$i++){
?>
<button id="text<?php echo $i; ?>">hello </button>
<script>
var i=<?php echo $i; ?>;
$(document).ready(function(){
$("#text"+i).click(function(){
alert("hello");
})
})
</script>
<?php } ?>
If I have a varying id like this and I want to call it in jQuery using this code its give me no result. Where is the problem? How can I call an element like this button?
Would be better to move the script out of the loop, get the buttons all at once and then bind the click event:
// Create all buttons, with class "text-button"
<?php for($i=0;$i<5;$i++): ?>
<button class="text-button" id="text<?php echo $i; ?>">hello </button>
<?php endif; ?>
<script>
// On document ready
$(document).ready(function() {
// Find all buttons with class "text-button"
$(".text-button").click(function(e) {
alert("hello");
// Log the clicked button
console.log(e.currentTarget);
console.log(e.currentTarget.id);
})
})
</script>
I am satisfied with #Emre's answer. And also remove $(doucment).ready() will solve your problem. Like this.
<?php
for($i=0;$i<5;$i++){
?>
<button id="text<?php echo $i; ?>">hello </button>
<script>
var i=<?php echo $i; ?>;
$("#text"+i).click(function(){
alert("hello");
});
</script>
<?php } ?>
I'm trying to get the id from a div tag and to console.log it but i get undefined.
Any ideas why is that happened?
<?php $id = get_the_ID(); ?>
<div class="about-cont" id="<?php echo $id ?>"></div>
<script>
jQuery('.about-cont').click(function(el){
console.log(jQuery(el.target).attr('id'));
});
</script>
Try with this.
<script>
jQuery('.about-cont').click(function(){
console.log(jQuery(this).attr('id'));
});
</script>
You can use event argument to easily find the clicked target. Also, you can prevent all the events related to that action by using event.preventDefault(); in the function block.
<script type='text/javascript'>
jQuery('.about-cont').click(function(event){
console.log(jQuery(event.currentTarget).attr('id'));
//or
console.log(jQuery(event.target).attr('id'));
});
</script>
You can Do like this, (this.id) is fetch current element id.
<?php $id = 1; ?>
<div class="about-cont" id="<?php echo $id ?>">click</div>
<script>
jQuery('.about-cont').click(function(el){
console.log(this.id);
});
</script>
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 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.