I have many links which are dynamically created with PHP and now I want to add an onclick event.
while($row = mysqli_fetch_array($xyz)) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . "</a></td>";
echo "</tr>";}
but I want like this:
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . onclick="test()"</a></td>";
echo "</tr>";}
is this possible?
I am not sure if I understood what exactly you are asking but I try to answer you the same:
You can't record a normal JS variable in a page session and then to access to it after the loading of a page.
For this case you can use cookies (that are accessible via server-side too):
// put this code into methods that users suggested you.
document.cookie = "value_selected=something"
and once page is loaded:
var cookies = document.cookie.split(';');
var value_selected = JSON.parse(JSON.stringify(cookies[YOUR_COOKIE].split("=")[0]))
or server side:
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" data-something=htmlentities($_COOKIE['value_selected']) target=\_blank>" . $row['z'] . "</a></td>"; //(example)
Or more simply, pass the value selected through query
?value_selected=something //elaborate the new link in the method users suggested you
and
in server-side, use $['GET'] to obtain all values in query string.
IMHO I think the first choice is simpler than second.
I hope I helped you
Try Like this
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a class='myclick' href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . **onclick="test()"**</a></td>";
echo "</tr>";}
i have added a class to link as myclick
and in jquery
$(document).on('click','.myclick',function(e){
e.preventDefault();
alert('clicked');
});
You can try like this..just a simple way.
<script type="text/javascript">
function test(){
alert('test');
}
</script>
<?php
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href='your link' onclick='test()'></a></td>";
echo "</tr>";
}
?>
Related
I am currently reading through a piece of code provided by my faculty and I am having troubles understanding how it works.
Specifically how the anchor is linked to the php without method="post" or method="get".
Kindly appreciate if anyone could explain or link me to relevant materials to do further readings. Much thanks.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Cart for bought items indexes is created in session if it's not there yet.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
When link with buy query parameter is opened, buy value is added to session cart. After that page is redirected to location without buy parameter.
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
List of items to buy is printed on page (i quess code in question is not full).
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Links open pages with GET method.
Link query parameters can be accessed by special $_GET variable
I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});
I'm working with PHP, Javascript and MySQL. My goal is to have a button on each row. The button should call the onclick fucntion and href to another page.
My problem with my code -- > only the button from the first row is clickable...
I'm assuming the Button ID needs to be unique for each button.. What are my options to make all buttons clickable ?
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'> $row[5]</td>";
echo "<td>$row[4] min(s)</td>";
echo "<td><img src='/iframe/$row[6]'> $row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementById('greenbutton').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
}
echo "</table></center>";
You're id's of your dom elements should be unique at all time. To achieve this you can add a counter in your while so that all of your button have an id like 'greenbutton1', 'greenbutton2', 'greenbutton3', etc.
$cnt = 1;
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton$cnt' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'> $row[5]</td>";
echo "<td>$row[4] min(s)</td>";
echo "<td><img src='/iframe/$row[6]'> $row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
$cnt++;
}
echo "</table></center>";
In that exemple I didnt add your javascript function into your while loop because it look like the same function for all your buttons. I suggest you add the function only once but bound it with the class selector instead of the id selector like this.
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementsByClassName('myGreenButtons').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
And then add the myGreenButtons class to your buttons in the while loop. You can also use attributes or types selector to gather your dom elements in a more flexible way. Check out theses links for more info:
http://www.w3schools.com/cssref/css_selectors.asp
http://www.htmlgoodies.com/beyond/javascript/using-javascripts-css3-selectors.html#fbid=FhIuAA6GqpH
hope this helps!
echo "<td><a href='/user'><button class='small pill green'>$row[0]</button></a></td>";
...will do the trick.
I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.
I'm working on a offine web application. But on a certain point it need to receive data from a sql database. This is done with an iframe. However the PHP files print all the data available. Every row of data has a workID, and i want them to be clickable. When you click on the work ID i need to save the work ID as variable so i can use the work ID through my whole application.
For example: I choose 1 work ID. Onclick the work ID is written in my header on every page.
I don't know if this can be done with cookies or just a javascript function on the main page.
See the following code:
<?php
$result=mysql_query("SELECT workid,problem,request FROM workreport ORDER BY workid;");
$i=0;
while( $row=mysql_fetch_array($result) )
{
if($i>0)
{
echo "<tr valign=bottom>";
echo "</tr>";
}
echo "<tr valign=center>";
echo "<td class=tabval></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['workid'])."</b></button></td>";
echo "<td class=tabval>".htmlspecialchars($row['problem'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['request'])." </td>";
$i++;
}?>
PHP is loaded in an iframe. So i prefer to create the function to save the work id on my main page.
<iframe src="http://localhost/receive.php" width="400" height="300" style="border:none;"> </iframe>
Hope you can help me! thanks in advance.
You can do it like this, using javascript and PHP:
PHP:
while( $row=mysql_fetch_array($result) )
{
if($i>0)
{
echo "<tr valign=bottom>";
echo "</tr>";
}
echo "<tr valign=center>";
echo "<td class=tabval></td>";
echo "<td class=tabval><button id=\"saveid\"><b>".htmlspecialchars($row['workid'])."</b></button></td>";
echo "<td class=tabval>".htmlspecialchars($row['problem'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['request'])." </td>";
$i++;
}
Javascript
window.onload = function () {
document.getElementById('saveid').onclick = function () {
var id = this.innerHTML;
document.cookie = "saveid=" + id + ", expires=Monday, 04-Apr-2020 05:00:00 GMT";
alert('Cookie saved!');
}
}
Okay, the cookie is now saved. You can access it in PHP using $_COOKIE['saveid'].