Javascript popup only showing the last result in PHP query - javascript

I have the following block of code and I'm not sure how to do what I'm wanting to do.
In essence I'm wanting the javascript popup to display that row's value, but (obviously) it's only showing the final row of data as the popup isn't set for each row but rather calls the variable when clicked.
Any help would be appreciated!
<?php
$result = mysql_query("SELECT hr_overtime.overtime_id, hr_user.name, hr_overtime.overtime_date, hr_overtime.overtime_type, hr_overtime.overtime_from, hr_overtime.overtime_to, hr_overtime.overtime_amount, hr_overtime.details
FROM hr_overtime
inner join hr_user
on hr_user.user_id = hr_overtime.user_id
where hr_overtime.overtime_status = 'Pending' order by hr_overtime.overtime_date ASC");
echo "
<table border='0'>
<tr>
<th class='tablecell_header'>Consultant</th>
<th class='tablecell_header'>Date</th>
<th class='tablecell_header'>Type</th>
<th class='tablecell_header'>From</th>
<th class='tablecell_header'>To</th>
<th class='tablecell_header'>Amount</th>
<th> </th>
<th> </th>
<th> </th>
</tr>";
while($row = mysql_fetch_array($result))
{
$work = $row['details'];
echo "<tr>";
echo "<td class='tablecell'>" . $row['name'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_date'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_type'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_from'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_to'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_amount'] . "</td>";?>
<td class='tablecell'> <button onclick="myFunction()">Show work</button> </td><script>
function myFunction()
{
alert("<?php echo $work;?>");
}
</script>
<?php
echo "<td valign='middle'><form action='manager_overtime_approve.php' method='post'>
<input name='approve_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='APPROVE' id='edit' />
</form></td>";
echo "<td valign='middle'><form action='manager_overtime_reject.php' method='post'>
<input name='cancel_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='REJECT' id='edit' />
</form></td>";
echo "</tr>";
}
echo "</table>";
?>

There is no need for a separate function which you are using incorrectly. You can simply use an inline alert for this:
<td class='tablecell'> <button onclick="alert('<?php echo $work;?>');">Show work</button>

You can't insert the declaration of myFunction() inside your foreach loop, that way you are overriding for each entry the behaviour showed thus it's only working for the last row.
one fast solution would be to insert the whole $work variable as an argument of your onclick function eg.
<td class='tablecell'> <button onclick="myFunction('<?php echo $work ?>')">Show work</button>
and then outside of the foreach loop you can define myFunction such as:
function myFunction(details){
alert(details)
}

I think, in result HTML you have a multiple definitions of myFunction() and javascript uses only last one. You can use a HTML tag attributes to show right information.

try this
$work .= $row['details'];
and set javascript out of the loop
good luck

That's because myFunction is a Javascript function, which is defined once and doesn not share the same scope as PHP. So $work hold just the last value.
I'd suggest something like this:
echo "<tr data-detail-value='$work'>";
...
<td class='tablecell'> <button onclick="myFunction(this)">Show work</button>
...
function myFunction(btn) {
alert(btn.parentNode.parentNode.getAttribute("data-detail-value"));
}

Related

How to pass PHP variable from a loop and use it as a Javascript variable

I have a while loop that displays some data into a table from a mysql table. Each table row has a button that is used to send data via ajax to another php page that insert the data into another table. My problem is that I want to get the values of specific rows by getting their ids but because I'm outside of the loop, I'm not able to the $row variable... How can I do such a thing?
Here is the portion of the code:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['TROUBLE_TICKET_NUM'] . "<input type=\"hidden\" name=\"billet".$row['TROUBLE_TICKET_NUM']."\" id=\"billet".$row['TROUBLE_TICKET_NUM']."\" value=\"".$row['TROUBLE_TICKET_NUM']."\"></td>";
echo "<td>" . $row['CONCAT(Year(activites.ACTIVITY_CREATE_DTM),month(activites.ACTIVITY_CREATE_DTM))'] . "</td>";
echo "<td>" . $row['CUSTOMER_NM'] . "</td>";
echo "<td>" . $row['DEFAULT_WORK_GROUP_CD'] . "</td>";
echo "<td>" . $row['ACTIVITY_OWNER_NM'] . "<input type=\"hidden\" name=\"id".$row['TROUBLE_TICKET_NUM']."\" id=\"id".$row['TROUBLE_TICKET_NUM']."\" value=\"".$row['ACTIVITY_OWNER_NM']."\"></td>";
echo "<td>" . $row['groupe'] . "</td>";
echo "<td>" . $row['Technicien'] . "<input type=\"hidden\" name=\"technicien".$row['TROUBLE_TICKET_NUM']."\" id=\"technicien".$row['TROUBLE_TICKET_NUM']."\" value=\"".$row['Technicien']."\"></td>";
echo "<td>
<label for=\"date". $row['TROUBLE_TICKET_NUM'] ."\"><strong>Date:</strong></label>
<input type=\"text\" name=\"date". $row['TROUBLE_TICKET_NUM'] ."\" id=\"date". $row['TROUBLE_TICKET_NUM'] ."\" onClick=\"ds_sh(this);\" value=\"".date("Y-m-d")."\">
<label for=\"heure". $row['TROUBLE_TICKET_NUM'] ."\"><strong>Heure:</strong></label>
<input type=\"text\" class=\"timepicker\" name=\"heure". $row['TROUBLE_TICKET_NUM'] ."\" id=\"heure". $row['TROUBLE_TICKET_NUM'] ."\"></td>
<td><button type=\"button\" class=\"btn btn-success btn-block\" name=\"insert-data". $row['TROUBLE_TICKET_NUM'] ."\" id=\"insert-data". $row['TROUBLE_TICKET_NUM'] ."\" onclick=\"insertData()\">Ajouter suivi</button>
<br>
<p id=\"message\"></p>
</td>";
echo "<tr>";
}
} else {
echo "<tr><td><div class=\"alert alert-dark\" role=\"alert\">Aucun résultat</div></td></tr>";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<!-- Script pour envoi donnée via ajax -->
<script type="text/javascript">
$(document).ready(function(){
$("#insert-data<?php echo $row['TROUBLE_TICKET_NUM']; ?>").click(function(){
var billet=$("#billet<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var technicien=$("#technicien<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var id=$("#id<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var date=$("#date<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var heure=$("#heure<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
// Debug
console.log(billet, technicien, tid, date, heure);
// AJAX
$.ajax({
method: "POST",
url: "insert-data.php",
data: {billet:billet,technicien:technicien,id:id,date:date,heure:heure},
dataType: "JSON",
success: function(data) {
$(".message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
});
});
</script>
If your intent is to allow the user to only insert values that come from existing rows, then don't pass the values you want to insert to the AJAX target. Otherwise, the user could manually call the AJAX target and simply provide any values they want. Instead, send the ID of the source row, and update the AJAX target to lookup that row and then copy the values from it.
You can do this by putting the row id into a data attribute for each row:
<tr data-id="<?= $row['id'] ?>">
Then use a jquery selector that fires on click of the button to get that value for the clicked row. Something like:
$(this).parent().data('id')

Html Form Onclick function does not take dynamic value

I have a html table the gets its values from a postgres table,have used php to echo the table content.
There are n no of rows in my table, When I click on the row I want the values of that row to be used in another function,
My code to populate the table with sql values is
while($row1 = pg_fetch_assoc($result1)) {
echo "<tr>"
. "<td>{$row1['name']}</td>"
. "<td>{$row1['email']}</td>"
. "<td>"
. "<form id='form_id'>"
. "<input type='hidden' id='cord' value=$row1['lat']>"
. "<input type='hidden' id='cord1' value=$row1['lon']>"
. "<a onclick='submit_by_id()' >view</a>"
. "</form>"
. "</td>"
. "</tr>\n";
}
}
?>
The html table is displayed, But only the first row values are shown (in the alert box) when I click the onclick function , I don't know how to reset the form values on click or is there any other way to optimize it.
function submit_by_id() {
var geom=document.getElementById('cord').value;
var geom1=document.getElementById('cord1').value;
alert(geom);
alert(geom1);
}
<table>
<thead>
<tr>
<th>Name</a</th>
<th>Email</th>
<th>Click to view</th>
</tr>
</thead>
<tbody>
<tr>
<td>name1</td>
<td>email1</td>
<td>
<form id='form_id'>
<input type='hidden' id='cord' value=15><input type='hidden' id='cord1' value=73><a onclick='submit_by_id()' >view</a>
</form>
</td>
</tr>
<tr>
<td>name2</td>
<td>email2</td>
<td>
<form id='form_id'>
<input type='hidden' id='cord' value=16><input type='hidden' id='cord1' value=78><a onclick='submit_by_id()'>view</a>
</form>
</td>
</tr>
</tbody>
</table>
</div>
You are iterating using while loop, but it does not create dynamic form in each iteration. which means all form in row a same. and submit form does not specify which form to sumit. you can do something like this
while($row1 = pg_fetch_assoc($result1)) {
$i=0;
echo "<tr>"
. "<td>{$row1['name']}</td>"
. "<td>{$row1['email']}</td>"
. "<td>{$row1['device_id']}</td>"
. "<td>{$row1['last_login']}</td>"
. "<td>"
. "<form id='form_id"$i."'>"
. "<input type='hidden' id='cord".$i."' value=$latlon[0]>"
. "<input type='hidden' id='cord1".$i."' value=$latlon[1]>"
. "<a onclick='submit_by_id($i)' >view</a>"
. "</form>"
. "</td>"
. "</tr>\n";
$i++;
}
}
?>
in javascript
function submit_by_id(id) {
var geom=document.getElementById('cord'+id).value;
var geom1=document.getElementById('cord1'+id).value;
alert(geom);
alert(geom1);
}
when you are using multiple rows, your id cord1 and cord also repeating. make it dynamically vary to each row or use class to get the value.
Well as the tags indicate jQuery is allowed so i use jQuery.
You should not have multiple elements with the same id. Use a class instead:
. "<form id='form_id'>"
. "<input type='hidden' class='cord' value=$latlon[0]>"
. "<input type='hidden' class='cord1' value=$latlon[1]>"
. "<a onclick='submit_by_id()' class='glyphicon glyphicon-pushpin'></a>"
. "</form>"
To access it a nice way is to use closest to find the form the element is in:
function submit_by_id() {
var $form = $(this).closest('form');
var geom= $form.find('.cord').val();
var geom1= $form.find('.cord1').val();
alert(geom);
alert(geom1);
}
ID should be unique, you need to use class in your case.
Change
id='cord' and id='cord1'
to
class='cord' and class='cord1'
And your JS code
function submit_by_id() {
var geom=document.getElementById('cord').value;
var geom1=document.getElementById('cord1').value;
alert(geom);
alert(geom1);
}
to
function submit_by_id() {
var $form = $(this).parent();
var geom= $form.find('.cord').val();
var geom1= $form.find('.cord1').val();
alert(geom);
alert(geom1);
}

I want to display 1 record instead of displaying the whole Database, PHP

dbconnect.php
<form method="post" action="a.php">
<select name="taskOption" id="cust-id" onchange="showUser(this.value)">
<?php
include 'orderSelect.php';
echo '<option>View Order</option>';
while($row = mysqli_fetch_array($result)):;?>
<option value='<?php echo $row[0]; ?>'><?php echo $row[1]; echo " ";
echo $row[2]; ?></option>
<?php endwhile; ?>
</select>
</form>
a.php
<?php
include 'connect.php';
$q = intval($_GET['q']);
$sql = "SELECT id, firstname, lastname,productOne, quantity, price
FROM orderlist";
$result = mysqli_query($conn, $sql);
echo "<table >
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
$tquan = $row['quantity'];
$tprice = $row['price'];
$total = $tquan * $tprice;
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['productOne'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $total . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I got it working. IT display the record/ users that I want to see when something is selected from the drop down list, but the problem is it's displaying the entire database data. I only want to get that specific that of the selected person. Any Ideas how to solve this problem? I would appreciate it.
Image Example
I only wanted the first row to be selected when I select from the dropdown list
Your SELECT is of the whole database you need to select something exact.
For example:
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
That is an example of using the WHERE clause.
In addition to what the above said.
You mentioned you only wanted 1 record.
Add " LIMIT 1" to the end of your query
OR
Change the 'while' command to an 'if' command and it will only run once.

Checking if checkboxes in PHP are checked using javascript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'>
<tr>
<th></th>
<th>Document No</th>
<th>AWB NO</th>
<th>Order Id</th>
<th>Forms</th>
<th>Extras</th>
</tr>";
foreach ($cancel as $key => $value)
{
echo "<tr>";
echo "<td>" . "<input type='checkbox' name='name1' id='checkit$checkitCounter' />" . "</td>";
echo "<td>" . $value[$d] . "</td>";
echo "<td>" . $value[$a] . "</td>";
echo "<td>" . $value[$o] . "</td>";
echo "<td>" . $value[$f] . "</td>";
echo "<td>" . $value[$e] . "</td>";
echo "</tr>";
}
echo "</table></div>";
This above table is generated using php echo with checkbox generated every iteration.
<div style="padding-left:600px;">
<a href='#' class='btn btn-primary btn-md' id='button' style="margin-right:1000px;" onclick='checkit()'
role='button'>Continue..</a>
</div>
The above button is supposed to run a javascript function given below:
function checkit {
var x = document.getElementById("checkit").checked;
if (x == false) {
alert('All items are not removed,pls remove and continue');
}
else {
window.location = "tst.php";
}
}
The above JavaScript doesn't seem to be functioning properly as even though i have checked none of the boxes it just stays on the same page.
Example:
<div style="padding-left:600px;"> <a href='#' class='btn btn-primary btn-md' id='button' style="margin-right:1000px;" onclick='checkit()' role='button'>Continue..</a>
</div>
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
<input type='checkbox' name='name1' class='checkit' />
And js:
function checkit() {
var boxes = document.querySelectorAll(".checkit");
arr = [];
for (i = 0; i < boxes.length; i++) {
arr.push(boxes[i]);
}
console.log(arr);
function is_checked(val) {
return val.checked == true;
}
checked = arr.filter(is_checked);
console.log(checked);
if (checked.length != boxes.length) {
alert('All items are not removed,pls remove and continue');
} else {
window.location = "tst.php";
}
}
Demo: https://jsbin.com/cukuzeweza/edit?html,js,output
I have made a light version of your code and the rest is left to your development logic.
You have had a lot small problems in your code, like function in JavaScript needed (), the usage of single and double quotes, missing call the JavaScript function etc.
I have created a dummy array for test, but again you could do what you like to achieve your code.
Here is the working solution:
<?php
$cancel = ["checkBox1", "checkBox2", "checkBox3"];
echo "<div><table id='data' class='table'>
<tr>
<th></th>
<th>Document No</th>
</tr>";
foreach ($cancel as $value)
{
echo "<tr>";
echo "<td><input type='checkbox' name='name1' id='$value' onchange='checkIt(\"$value\");' /></td>";
echo "<td>" . $value . "</td>";
echo "</tr>";
}
echo "</table></div>";
?>
<script>
function checkIt(checkBoxId) {
var x = document.getElementById(checkBoxId).checked;
console.log("x" + checkBoxId + " is " + x);
}
</script>
You can see in your console the results of your checkbox.

Expand/Collapse table row Javascript works wrongly

I'm using this code to expand database table row to reveal more information about the item, but it does exactly the opposite.
$("td span.expand").click(function() {
$(this).parents("tr.main").nextUntil("tr.main"). toggle();
});
When I open the table all rows that must be hidden are being shown and if I click on any main row it will hide that rows.
How to invert this?
Here's part of code I use for table (I know, it's messy):
echo '<table border="1" class="tabula">
<tr class="main">
<th width="30px">Nr.</th>
<th width="75px">Mašīnas numurs</th>
<th width="75px">Reģistrācijas numurs</th>
<th width="75px">Marka / Modelis</th>
<th width="75px">ID</th>
</tr>';
//Ieraksta datus tabulā
while($row = mysql_fetch_array($query))
{
echo "<tr class='main'>";
echo "<td width='30px'>" . $row['nr'] . "</td>";
echo "<td width='75px'>" . $row['numurs'] . "</td>";
echo "<td width='75px'><span class='expand'>" . $row['regnr'] . "</span></td>";
echo "<td>" . $row['modelis'] . "</td>";
echo "<td>" . $row['apzim'] . "</td>";
echo "</tr>";
echo "<tr class='hidden'>";
echo "<td>text</td>";
echo "<td>text</td>";
echo "<td>text</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
Try using CSS in your file and include the following:
<style>
.expand
{
display:none;
}
</style>
I use a jQuery-based toggle script, and that's what I used when I had a similar problem such as this.
You may need to use .hidden { display:none; } instead.

Categories