PHP and Javascript : Multiple Buttons inside a table - javascript

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]'>&nbsp$row[5]</td>";
echo "<td>$row[4]&nbspmin(s)</td>";
echo "<td><img src='/iframe/$row[6]'>&nbsp$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]'>&nbsp$row[5]</td>";
echo "<td>$row[4]&nbspmin(s)</td>";
echo "<td><img src='/iframe/$row[6]'>&nbsp$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.

Related

Add onclick event to a dynamic created link (PHP)

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>";
}
?>

Getting text and sending it to a php function using javascript

I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>

I am trying to update records by php code. but having trouble in my code

I am trying to update records by php code. but having trouble in my code.
code is running without using functions (get40(),show()) but i want to use buttons to call these functions.
code is give below:
this is main code file:
<?php
$data;
$count=0;
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
$result;
$query;
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
function get40($off='0', $rcd='2')
{
global $db,$result,$query;
$query="SELECT sword, tword, reviewed from TempDictionary LIMIT $off,$rcd";
$result = $db->query($query)or trigger_error($db->error);
}
function show()
{
global $db,$result,$query;
echo "<form action='testSave.php' method='POST'>";
echo "<table border=1 >";
while($row = mysqli_fetch_array($result))
{
global $count;
$count+=1;
echo "<tr>";
echo "<td><input type='text' name='s[]' value=" . $row['sword'] . "></td>";
echo "<td><input type='text' name='t[]' value=" . $row['tword'] . "></td>";
echo "<td><input type='text' name='r[]' size='1' value=" .$row['reviewed'] . "></td>";
echo "</tr>";
}
echo "</table>";
echo "<input type='text' name='no' size='2' value=" .$count. ">";
echo "<input type='submit' value='Save'>";
echo "</form>";
}
//get40(1,2);
//show();
mysqli_close($db);
?>
<script type="text/javascript">
function get()
{
<?php
get40(0,3);
show();
?>
}
</script>
<form action="" method="POST">
<input type=button name=btnGet value=Get onclick="get()">
</form>
and savetest.php file is:
<?php
$no=$_POST['no'];
$i=0;
$s=$_POST['s'];
$t=$_POST['t'];
$r=$_POST['r'];
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
// display
foreach ($s as $key=>$value)
{
print "$key = $value $t[$key] $r[$key]";
echo '<br>';
}
// save to DB
foreach ($s as $key=>$value)
{
// $query="UPDATE TempDictionary set sword=".$value.",tword=".$t[$key].",reviewed=".$r[$key]."
// WHERE sword=".$value;
$query="UPDATE TempDictionary set sword='$value',tword='$t[$key]',reviewed='$r[$key]'
WHERE sword='$value'";
$result = $db->query($query)or trigger_error($db->error);
}
mysqli_close($db);
?>
the problem is while i click button it does not works.
AFAIK you are trying to run PHP code with Javascript code.
Use Jquery/Ajax to solve your problem. You can Google for that or look at stackoverflow.
Step 1: Learn how a click on a button can run PHP
Run php function inside jQuery click
Step 2: Learn how to use data from a database and populate a form with it:
ajax call to populate form fields from database query when select value changes
That's the first step in solving your problem. (sorry it's no copy/paste solution, just a pointer in the right direction)

Save Id from PHP database as variable

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'].

How to use the data from the row selected?

How can I collect the data on the row from the table that I select and use it in the result?
Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in PHP that will include (1) some of the data from the row selected and (2) some new data that will be collected.
Here is the Javascript to select the row and call the data entry form
$(document).ready(function () {
$("tr").live('click',function(){
$.post('data_entry_form.php', function(data) {
$('#section2').html(data);
});
});
});
Here is the PHP Script
<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
echo "<table id=\"all_aifs\">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";
foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
$dbh = NULL;
?>
The "Correct" answer to this problem is NOT to read from the DOM. Never a good idea. I suggest you pass the record id to the ajax call and have the ajax call return an already-populated form.
//PHP
//place the data attribute in the tr
echo "<tr data-recordId='".$row['id']."'>";
//JS
$(document).ready(function () {
$("tr").live('click',function(){
//Get the ID from the row clicked
var id = $(this).data('recordId');
//short-hand
$('#section2').load('data_entry_form.php?id='+id);
});
});
Then your ajax page would just read $_REQUEST['id'] to get the id of the form being edited.
//Ajax side PHP
$id = (int)$_REQUEST['id'];
//Fetch data and use it to pre-populate form item
You would pre-populate your inputs like this
<input type="text" value="<?php echo $row['value']; ?>" />
or
echo '<input type="text" value="'.$row['value'].'" />';
NOTE: If your values contain quotes, you will want to replace them with the code "
echo '<input type="text" value="'.str_replace('"', '"', $row['value']).'" />';
Within the event handler, this and $(this) refer to your selected row:
$("tr").live('click',function(){
// this.cells[1] is the cell that contains Pubco Name
// You can also use $(this).children("td")[1]
...
});

Categories

Resources