PHP sql table onclick event - javascript

I have a php script building a table. I need from the php to define a onclick event for each row forwarding to a function.
currently not successful to call the function.
while($row = $result->fetch_assoc()) {
echo "<tr onclick="myFunction(this)" >
<td>".$i."</td>
<td>".$row["dest"]."</td>
<td>".$row["tool"]."</td>
<td>".$row["air_port"]."</td>
<td>".$row["ctry_cd2"]."</td>
<td>".$row["geo"]."</td>
<td>".$row["carrier_td"]."</td>
<td>".$row["required_dd"]."</td>
<td>".$row["carrier_dd"]."</td>
<td>".$row["TPT"]."</td>
<td>".$row["sqf"]."</td>
<td>".$row["Weight_kg"]."</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
echo $selected_sqf;
echo $selected_weight;
?>
<script>
function myFunction(x) {
echo 12;
alert("Row index is: " + x.rowIndex);
}
</script>

I think what you want to do is change
echo "<tr onclick="myFunction(this)" >
to
echo "<tr onclick=\"myFunction(".$i.")\"> or any other ID you expect inside it
You can easy test it with this:
<?php
for ($x = 1; $x <= 3; $x++) {
echo "<button onclick=\"myFunction(".$x.")\">test it</button><br>";
}
?>
<script>
function myFunction(x) {
alert("Row index is: " + x);
}
</script>

onClick won't work this way for dynamically created elements.
You can use delegated event call using jQuery as:
$("table").on("click", "tr", function(){
//Enter your code here
});

Related

Can i pass array to an HTML? Creating a dynamic html table with php/javascript

I have created a table with 3 columns and rows with the size of an array pulled from the database. I have got the value but I want to create a button inside the cells with the name from pname and when you click that button it will take you to the value of plink. I tried using <input type="button" value=" " onclick="window.open( )", but it doesn't seem to pass the arrays. I am sure there is an easier/ better way to do it with JavaScript, but I am not familiar with JavaScript. Please help me out. Here is my code.
I want the format 3 columns and infinite rows(based on the data).
<!DOCTYPE html>
$pname = array();
$plink = array();
$results = $wpdb->get_results("SELECT name, link FROM `wptable`);
if(!empty($results)) {
foreach($results as $row){
$pname[] = $row->name;
$plink[] = $row->link;
}
}
$num = 0;
echo "<table class='table'>";
echo "<tbody>";
echo "<br><br>";
$quant_row = count($pname)/3;
$quant_col = 3;
for ($count_row = 0; $count_row < $quant_row; $count_row++)
{
echo "<tr>";
for ($count_col = 0; $count_col < $quant_col; $count_col++)
{
echo "<td>";
echo $plink[$num];
echo "</td>";
$num++;
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
You just need to echo a button inside an anchor:
echo '<button type="button">' . $pname[$num] . '</button>';
try this.
echo "<td>";
echo "<button onclick=\"Document.getElementById('link$num').display=state$num? 'none' :'block';state$num=!state$num; \">". $pname[$num] ."</button><div id='link$num'>". $plink[$num]."<div>";
echo "";
when you click on $pname , you show the $plink. reclick and hide the content

jQuery show/hide is not working

I have following loop in php:
foreach ($sid as $key => $value) {
$sql = " a sql query ";
$vehicle->rowQuery($sql);
$numRows = $vehicle->rows;
while ( $data = $vehicle->result->fetch_assoc()) {
$vid = $data['vid'];
$vehicleName = $data['vehicleName'];
$noOfSeat = $data['noOfSeat'];
$seatBooked = $data['seatBooked'];
$supplierName = $data['supplierName'];
echo "<table class='table table-bordered table-condensed table-striped'>";
echo "<tr>";
echo "<th colspan='4' class='success'>
<label class='checkbox-inline'>
<input type='checkbox' class='vehicleClass' name='vid[]' value='{$vid}'>$vehicleName<strong> ( $noOfSeat Seats available) - $supplierName
</label>
<div class='pull-right'><a href='#' class='hideMe'>Show/Hide</a></div></strong>
<input type='hidden' name='noOfSeat[$vid]' value='$noOfSeat'>
</th>";
echo "</tr>";
echo "<tr>";
echo "<th colspan='4'>All Seats</th>";
echo "</tr>";
$count = 0;
for ($seat=1; $seat <= $noOfSeat; $seat++) {
if($count % 4 == 0) {
echo "</tr><tr class='toggleMe'>";
}
echo "<td><label class='checkbox-inline'><input type='checkbox' name='seatNo[$vid][]' value='$seat'>Seat $seat </label></td>";
$count++;
}
echo "</table>";
}
if( $numRows == 0 ) {
echo "<table class='table table-bordered table-condensed table-striped'>";
echo '<tr><td class="alert alert-warning">Your selected vehicle is not available.</td></tr>';
echo "</table>";
}
}
It's output is like that:
Now, I am trying to show and hide the corresponding All Seats Checkbox list whne I click on show/hide link using following jQuery:
$(document).ready(function(){
$('.hideMe').click(function() {
$(this).next('.toggleMe').toggle();
});
});
But show/hide it's not working. Can you guys tell me how can I solve it?
Thanks.
===================
Update:
When the loop result is this :
then using this code it's working fine:
$(document).ready(function(){
$('.hideMe').click(function() {
$('.toggleMe').toggle();
});
});
Do you use ajax to get the html?
if yes, you had better use $('body').on('click,'.hideMe',function() {})
and tr is not next element of .hideMe
You can try this code.
$(document).ready(function(){
$('body').on('click','.hideMe',function() {
$(this).parents('table').find('.toggleMe').toggle();
});
});
I think you should use on('Click',function(){ }) instead of click try this
$(document).ready(function(){
$('body').on('click', '.hideMe', function() {
$(this).next('.toggleMe').toggle();
});
});
I think your structuring with "<tr>" is not correct in
if($count % 4 == 0) {
echo "</tr><tr class='toggleMe'>";
}
this will add a </tr> at the beginning of each toggleMe class.

How to get value of checkbox from PHP and DOM

i need to know how on earth to get my checkbox value from PHP that is in a loop and also might be in DOM. I have to put that checkbox inside the loop to make it being shown on each row of databases. I tried to call it back using different method but none success. The last part is javascript but i don't have any clue how to do that.
My code for javascript index.php.
function ajaxSearchUpdater(p){
$("#result").show();
var x = $("#search").val();
var y = $("#edulevel").val();
var pagelim = $("#pagefpe").val();
var pagenumber = p;
var checkb = $(".sBorrow").val()
$.ajax({
type:'POST',
url:'userres.php',
data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(1); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(1); // your function call
});
$("#edulevel").click(function() {
ajaxSearchUpdater(1); // your function call
});
$("#pagefpe").click(function() {
ajaxSearchUpdater(1); // your function call
});
$('.sBorrow').on('change', function(){
var checkBorrow = $(event.target);
var isChecked = $(checkBorrow).is(':checked');
alert("test");
alert(isChecked);
alert('checkbox'+checkborrow.attr('id')+'is checked:'+isChecked);
});
});
$(document).ready(function() {
$('.sBorrow').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
My code for the checkbox in PHP userres.php
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Thesis Level</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Select book (Max 3)</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
$sBorrow = $_SESSION['sBorrow'];
echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
<form method='post'>
<input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
</form></td></tr>";
$startrow++;
//echo $row['education_level'];
}
echo "</tbody>";
echo "</table>";
I don't know what to do since i'm calling that page from ajax and uhh how should i explain this.
You know index.php -> userres.php -> index.php using ajax.
for javascript on the bottom part is what i have done and i dont think its right. I tried to create one other document ready for this checkbox but still even alert not showing up. I'm confused. please help T_T

How to delete dynamically created table rows without refreshing (preferentially with the standard swipe-to-left-animation)

Sorry, but I have to ask one more question. Google couldn´t help me :(
I try to create a user control management in a CMS.
The problem is that I am completely knew to javascript and jQuery and I have to delete a table row on button click without refreshing the page. The idea is to set the row display:hidden, but I don´t know how to get the id of a row.
Here is my code:
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY id asc");
//$ergebnis = mysql_query($abfrage) or die( mysql_error() );
echo "<table>";
echo"<caption>Mitglieder<br></caption>";
echo"<table border=\"1\" style=\"width:300px\">";
echo "<th>ID</th>
<th>Name</th>
<th>Vorname</th>
<th>Rolle</th>
<th>Funktionen</th>";
//loop, um alle Nutzer zu identifizieren
while($row = mysql_fetch_object($abfrage))
{
echo "<tr>";
echo "<td align=center id =",$row->id,">",$row->id,"</td>";
echo "<td align=center>" ,$row->Name,"</td>";
echo "<td align=center>",$row->Vorname,"</td>";
//Vorbelegung
echo "<td align=center><select><option selected = \"selected\">",$row->Rolle,"</option>";
//loop, um alle Rollen zu identifizieren. AKTUELL: doppelte Rollen werden noch doppelt angezeigt. Eventuell Rollen auslaagern
$file = mysql_query("SELECT Rolle FROM user WHERE 1");
while ($role = mysql_fetch_row($file))
{
if ($role[0]!= $row->Rolle) {
echo "<option value=".$role[0].">",$role[0],"</option>";
}
}
echo "</select></td>";
echo "<td align=center><button type = \"button\" onCLick = \"deleteUser()\">Löschen</button></td>";
}
echo "</table>";
?>
<html>
<script type="text/javascript">
function deleteUser() {
alert("And it works");
document.getElementById(id).style.display = 'none'
}
</script>
</html>
The problem is here:
echo "<td align=center id =",$row->id,">",$row->id,"</td>";
Is this the right way to create an id to every row?
And if somebody knows how to realize it, I want to have an "deleting" (Deleting is obviously the wrong word because it is only hidden) animation.
Thank you in advance!
Ps: I know, that I have to change mysl to SQLi :)
I'm not really a FAN of JQuery because makes you forgeth the very basics of Javascript! it really simplyfies some things but... hmm dunno!
maybe this "function" could help you:
function dropRow(rowId) {
try {
var tblResponse= document.getElementById('tblResponse');
var rowCount = tblResponse.rows.length;
for(ix=0; ix < rowCount;ix++) {
var row = tblResponse.rows[ix];
var id = row.cells[0].childNodes[0].id; //The ID of something what identifies the Row
if(id == 'dropRow'+rowId) {
tblResponse.deleteRow(ix);
rowCount--;
ix--;
}
}
}catch(e) {
alert(e);
}
}
You can use the remove function within jQuery.
You will want to give the ID to the <tr> and not a <td> within the row, next your deleteUser function should take the "id" as an argument, and finally you should delete the row from within the deleteUser function. But you will need a way to inform your database that the user has been deleted, perhaps ajax to an API might work but I don't know how you have your system set up.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function deleteUser(id){
$(id).remove();
// Do something to let the server know the user was deleted
}
</script>
</head>
<body>
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY id asc");
echo "<table>";
echo "<caption>Mitglieder<br></caption>";
echo "<table border=\"1\" style=\"width:300px\">";
echo "<thead><tr><td>ID</td><td>Name</td><td>Vorname</td><td>Rolle</td><td>Funktionen</td></td><thead>";
while($row = mysql_fetch_object($abfrage)){
echo "<tr id='".$row->id."'>";
echo "<td align='center'>".$row->id."</td>";
echo "<td align='center'>".$row->Name."</td>";
echo "<td align='center'>".$row->Vorname."</td>";
echo "<td align='center'><select><option selected=\"selected\">".$row->Rolle."</option>";
$file = mysql_query("SELECT Rolle FROM user WHERE 1");
while ($role = mysql_fetch_row($file)){
if ($role[0]!= $row->Rolle)
echo "<option value=".$role[0].">".$role[0]."</option>";
}
echo "</select></td>";
echo "<td align='center'><button type = \"button\" onclick = \"deleteUser(".$row->id.")\">Löschen</button></td>";
echo "</tr>"
}
echo "</table>";
?>
</body>
</html>

calling a php function in javascript

I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};

Categories