How to use onclick in table?
The following code is my basic code.
php code
$con = mysqli_connect($db_host,$db_user,$db_passwd,$db_name);
mysqli_set_charset($con, "utf8");
$result = mysqli_query($con, "select * from Marker_DB");
echo "<table border=’1′> <tr> <th>num</th> </tr>";
$n = 1;
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['num'] . "</td>";
echo "</tr>";
$n++;
}
echo "</table>";
mysqli_close($con);
I've made a lot of attempts to use onclick. Here's how I tried:
code
echo "<td>". "onclick='displayComment($row['num'])" . "</td>";
echo "<td onClick="'www.google.com/'">". $row['num'] . "</td>";
How can I use onclick in php?
Give your table some id,
echo "<table border='1′ id='table-id'> <tr> <th>num</th> </tr>";
Then your td will be as it is,
echo "<td>". $row['num'] . "</td>";
In js just write this code and check,
$("#table-id").on("click", "td", function() {
alert($(this).text()); // see if you get the value of $row['num']
// you can play here as you like
var num = $(this).text();
displayComment(num);
});
function displayComment(num) {
// your code
}
What you need to do is to stop the propagation of the parent event when a child is clicked, it's easy done in jQuery, but naively you need to do a little more work:
function displayComment(num){
//Do your stuffs with num
console.log('td clicked');
};
Note, for Firefox you need to pass a event parameter:
<td onclick="displayComment($row['num'])">Column 3</td>
Related
I'm currently using a combination of HTML, PHP, Javascript, and AJAX in order to create an HTML , populate it from a table in a MySQL database, then add a inside of the table in order to both remove the row, and delete the entry from the MySQL database as well. This is what I currently have:
<?php
echo '<table id="tag_table" border=1>
<tr>
<th>Tags</th>
<th>Delete Tag</th>
</tr>';
$iter = 0;
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
echo "<tr id=" . $iter . "\">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>";
echo "<button id=\"delete\">Delete</button>";
echo "</td> </tr>";
}
?>
Now what I want to do is add .click() functionality to the delete button, but I'm stuck because I want to delete the row using the following Javascript:
function deleteTag(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
But I also need to delete the corresponding entry in the MySQL database, requiring PHP (which I can't use inside the javascript file). If anyone has a possible solution or idea of how to accomplish these things, I'd be so grateful to know.
Thanks for any help.
Edit 1. My PHP code:
<?php
$db = new PDO('my info here bla bla bla');
$query = "DELETE FROM Tags WHERE name=" . $_POST['name'];
$db->exec($query);
$db = null;
?>
You can use the attribute onclick=? in your button tag in combination with your JS function: onclick=removeTag(this).
<?php
echo "
<table class="tag_table" border=1>
<tr>
<th>Tags</th>
<th>Delete Tag</th>
</tr>";
$iter = 0;
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row)
{
echo "<tr class=" . $iter . ">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>";
echo "<button onclick=\"deleteTag(this)\" class=\"delete\">Delete</button>";
echo "</td></tr>";
}
?>
JS:
function deleteTag(btn) {
// select the row that's concerned
var row = btn.parentNode.parentNode;
// select the name of this row
var name = row.children[0].textContent;
// remove the row on client side
row.parentNode.removeChild(row);
// AJAX call to remove the row server side
$.ajax({
url: 'removeRow.php', // this is the target PHP file
type: "GET",
data: ({
name: name
}),
success: function(data) {
// the following will be executed when the request has been completed
alert('Entry has been deleted successfully!');
}
});
}
PHP: the trick is you need to retrieve the variable sent by AJAX with $_REQUEST['...'] not with $_GET['...'] or $_POST['...']
<?php
if($_REQUEST['name']) {
// if the variable has been successfully received
$name = $_REQUEST['name'];
$db = new PDO('my info here bla bla bla');
$query = $db->prepare("DELETE FROM Tags WHERE name = :name");
$query->execute(array('name' => $name));
unset($db, $query)
}
So my objective was to print data from two into a standard table.
It should ideally display the name of the each distinct scholarship and its table with a list of all the students who applied for it. I m uncertain if my approach is correct.
Please help, i m trying to learn the basics. Thanks in advance.
<?php
include_once 'function.php';
connect();
?>
<html><body>
<?php
$query = "SELECT *
FROM entry, student_details
WHERE entry.user_id=student_details.user_id";
//run query
$result = mysql_query($query);
// creating a table
echo "<table border='1'>
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>";
//Print the record that matches the criteria of the query
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['s_name']
{
echo "<tr>";
echo "<td>" . $row['student_id'] . "</td>";
echo "<td>" . $row['student_name' ] . "</td>";
echo "</tr>";
}
}
?>
</table>
<?php close()
?>
</body></html>
the error i get is this Parse error: syntax error, unexpected 'echo' (T_ECHO) on line echo "<tr>";
Parse error messages don't necessarily originate on the actual line number stated, but many times one line above, being this:
echo $row['s_name']
-------------------^
// missing semi-colon
You forgot to put an ending semi-colon at the end.
Modify it to look like this:
echo $row['s_name'];
-------------------^
You have a syntax error.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['s_name'];
echo "<tr>";
echo "<td>" . $row['student_id'] . "</td>";
echo "<td>" . $row['student_name' ] . "</td>";
echo "</tr>";
}
Could somebody please point me in the right direction as regards refreshing a particular div using ajax. I know the basics of php, a little jquery, but Zero ajax. My scoreboard is built using php within a table as follows -
<div class="scoreBoard">
<table>
<?php
include("lib/inc/connect.php");
$sql="SELECT * FROM highScores ORDER BY Score DESC";
$result=mysqli_query($con,$sql);
$i = 1;
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row["Name"] . "</td>";
echo "<td>" . $row["Score"] . "</td>";
echo "</tr>";
$i++;
}
mysqli_close($con);
?>
</table>
</div>
At the moment I have a little refresh image that refreshses the page onClick via JS. The idea of an ajax refresh would be much nicer.
save your php code in a file named somename.php then call it with
ajax
in somename.php
<?php
include("lib/inc/connect.php");
$sql="SELECT * FROM highScores ORDER BY Score DESC";
$result=mysqli_query($con,$sql);
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row["Name"] . "</td>";
echo "<td>" . $row["Score"] . "</td>";
echo "</tr>";
$i++;
}
mysqli_close($con);
?>
in your main file
<div class="scoreBoard"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
setInterval( refreshScoreBoard, 5000 );
var inRequest = false;
function refreshScoreBoard() {
if ( inRequest ) {
return false;
}
inRequest = true;
var load = $.get('somename.php');
$(".scoreBoard").html('Refreshing');
load.error(function() {
console.log( "Error" );
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".scoreBoard").html('<table>'+res+'</table>');
});
load.done(function() {
console.log( "Completed" );
inRequest = false;
});
}
</script>
smth. like this in some event triggered function(can be time interval either):
$('.scoreBoard').load('path/to/php_fetching_data_and_building_table');
For more information (like sending post/get) check here:
jQuery - load
ps: you can also use 'ajax' jquery function
Ok so I have a script that pulls information from a database and puts it into a table. (the full script is at the bottom of this question)
Each TR is echoed with a standard ID: echo "<tr class='task' id='task1'>"; the only problem with this is each new tr or each row that is pulled from the database gets assigned the same ID task1 This is not good coding technique as well as not working with my javascript for changing the tables class name's based on the information from the database.
So my question is, is there a way to sort of "auto generate" the id name for each tr of the table? I would like to see task1, task2, task3 and so on.
Full code starts here
<?php
$con=mysqli_connect("");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM affiliate_tasks WHERE username = '$_SESSION[username]'";
if( isset($_POST['sort-selection']) && $_POST['sort-selection'] != 'all' )
{
$query .= " AND status = '". $_POST['sort-selection']."';" ;
}
$result = mysqli_query($con, $query);
echo "<table class='table table-message'>
<tr class='heading'>
<td class='cell-title'>Tasks</td>
<td class='cell-status hidden-phone hidden-tablet'>Status</td>
<td class='cell-time align-right'>Due Date</td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr class='task' id='task1'>";
echo "<td class='cell-ttle'>" . $row['task_name'] . "</td>";
echo "<td class='cell-status hidden-phone hidden-tablet'>" . $row['status'] . "</td>";
echo "<td class='cell-time align=right'>" . $row['due_date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
If your table row has an unique id column, that will be the best fit here. You can use:
echo "<tr class='task' id='task-" . $row['id'] . "'>";
If not, and you just want a sequential number, you just use a variable like this:
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr class='task' id='task-" . ++$i . "'>";
// Rest of your lines ...
}
Hi I have problem getting the value of select node posted and get nothing.
I am using dojo/request. And the getuser1.php at the server is working when I tested with simple ajax file.
At the request line, the values for data may not be correct
Please advise... Thanks
Following are two scripts:-
main.php file -
require(["dojo/parser", "dojo/ready","dijit/form/Select",
"dojo/request","dojo/on","dojo/domReady!"],
function(parser, ready, Select, request, on){
ready(function(){
console.debug('Rendering...');
var selectX = new Select({
name:'select_test',
options:[
{label:"<span class='NotinUse'><b>   . . .</b></span>", value:'0', selected:true},
{label:"<span class='inUse'><b>  Peter Griffin</b></span>", value:'1'},
{label:"<span class='inUse'><b>  Lois Griffin</b></span>", value:'2'},
{label:"<span class='inUse'><b>  Joseph Swanson</b></span>", value:'3'},
{label:"<span class='inUse'><b>  Glenn Quagmire</b></span>", value:'4'},
],
style:{width:'150px'}
},"select");
on(formNode2, 'Change', function(evt){
evt.stopPropagation();
evt.preventDefault();
request.post('getuser1.php',{
data:{select_test:this.value},
timeout:2000
}).then(function(response){
dom.byId('line2').innerHTML=response;
});
});
});
});
getuser1.php file:-
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = $q";
$result = mysql_query($sql);
// use stored function to return one result instead later. Write here after stored procedure has been stored.
echo "<table border='1'>
<tr>
<th width=100>Firstname</th>
<th width=100>Lastname</th>
<th width=100>Age</th>
<th width=100>Height</th>
<th width=100>Hometown</th>
<th width=100>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Height'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Remember to use your browser's error console when developing, it will often notify you of simple typos etc in your code.
In this case, there are a few things wrong. It seems you've mixed up selectX and formNode2. It should presumably be:
on(selectX, 'Change', function(evt){
Now, if you get this to work, you'll notice that when you change selectX's value, you'll get an error in your console:
evt.stopPropagation is not a function
This is because the evt argument is not actually an event object here. From select elements, you only get the new value, not the event. Change it to something like this, and you should see what I mean in the console:
on(selectX, 'Change', function( newValue ){
console.debug('The new value is', newValue);
//evt.stopPropagation();
//evt.preventDefault();
I made a few changes to make it work in jsfiddle, but it should give you an idea: http://fiddle.jshell.net/AmxKv/