PHP grab corresponding column id - javascript

I have the following html/php table:
<table id="blacklistgrid">
<tr id="Row1">
<td class="space"> </td>
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid=0");
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $('.columnname').text();
var id= $('.columnname').attr('id')
$.ajax({
type:"post",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
</tr>
<?php
$query=mysqli_query($mysqli, "SELECT name,memberid_fk FROM groupsort INNER JOIN members ON groupsort.memberid_fk=members.memberid WHERE group_id_fk=0");
while ($row=mysqli_fetch_array($query)){
echo' <tr id="Row2">';
echo' <td>';
echo'<h3>'.$row['name'].'</h3>';
echo'</td>';
$query=mysqli_query($mysqli, "SELECT submitted FROM userassignment WHERE userid=".$row['memberid_fk']." and groupid=0");
$row2=mysqli_fetch_array($query);
if ($row2['submitted']==0){
echo' <td>';
echo' <input type="checkbox" name="red" />';
echo' </td>';
}else if ($row2['submitted']==1) {
echo' <td>';
echo' <input type="checkbox" name="red" checked />';
echo' </td>';
}
echo' </tr>';
}
?>
</table>
Im creating a system to keep track of who submits their homework, so it is in the form of a table. On the left side would be all the names of people (in the class), and the right are individual columns with the names of various assignments.
I am using contenteditable to update the name of the assignment/ and also checkboxes to tick when a student/person submits his assignment.
However, in order to make the tick work, what happens is i need to get the corresponding .columnclass id (which i have assigned as the assignmentid), for me to update the correct field.
The issue now is that the columnclass php is in the front while loop, so im not very sure how to access the column class id from the second php whileloop. QUESTION: Is there a way for php to grab the id of the td(an element) without using javascript?
If user submitted assignment, the submitted row in my table would be 1, so then php would display checked checkboxes. However, as per its mysql query, i need to add the assignment id as well, which can be retrieved from the ID of the corresponding td columnclass id.
The table looks something like this:
Assignment 1 Assignment 2
Name1 CHECKBOX CHECKBOX
Name2 CHECKBOX CHECKBOX
Name3 CHECKBOX CHECKBOX
Name4 CHECKBOX CHECKBOX
So lets say i want to see if name1 submitted assignment1, then in my mysql table, i need to feed it both the userid AND the corresponding assignment id, therefore to retrieve the assignment id, i need to grab the id of the "assignment 1" .columnclass element's id (which i stored the value of assignmentid) I feel that this is a hack, is there a better way to do this?
Note i removed the add column/row code in the code snippet above to increase simplicity.
To make it even simpler to understand the table code above, the table is created like this:
(row 1) emptytd1 td2(assignment)..
(row 2) td1(name) td2(checkbox)..
.
.
To determine if td2 should be checked, i need to query the database, and to do that, since there are multiple users and multiple assignments, i need the name and the assignment, the name is easy to get since it is within the query, but the assignment is in the previous php while loop.

Looks like, when you get to listing out the users in your table, you're not looping over the existing assignments. What you have only writes to the first assignment column, regardless of what assignment the user submitted.
So, below are a few tweaks of your existing code. First I added two lines to your assignments header row, marked with comments. The first creates an assignments array (for later use), and the second loads that array with the existing assignments.
Then, when looping over the users, for each user I added a loop over the existing assignments array. This accomplishes two things, 1) it puts aligns the assignments to the appropriate column, and 2) it gives you the assignment id you need to check if the user submitted the assignment. (I also used prepared statements for added security.)
NOTE: I'm guessing that your "userassignment" table has a field named "a_id" that gets set along with "userid" when a user submits an assignment.
<table id="blacklistgrid">
<tr id="Row1">
<td class="space"> </td>
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid=0");
$assignments = array(); // create empty assignments array
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
$assignments[$row['a_id']] = $row['assignment']; // add assignment to array
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $('.columnname').text();
var id= $('.columnname').attr('id')
$.ajax({
type:"post",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
</tr>
<?php
$query=mysqli_query($mysqli, "SELECT name,memberid_fk FROM groupsort INNER JOIN members ON groupsort.memberid_fk=members.memberid WHERE group_id_fk=0");
while ($row=mysqli_fetch_array($query)){
echo' <tr id="Row2">';
echo' <td>';
echo'<h3>'.$row['name'].'</h3>';
echo'</td>';
// LOOP OVER ASSIGNMENTS ARRAY
foreach ( $assignments as $a_id => $assignment ) {
$query2=mysqli_prepare($mysqli, "SELECT submitted FROM userassignment WHERE userid=? and groupid=0 and a_id=?"); // added assignment id condition
mysqli_stmt_bind_param($query2, "ii", $row['memberid_fk'], $a_id);
mysqli_stmt_execute($query2);
mysqli_stmt_bind_result($query2, $submitted);
mysqli_stmt_fetch($query2);
$checked = ( $submitted )? 'checked': '';
echo" <td> <input type=\"checkbox\" name=\"red\" $checked /> </td>";
mysqli_stmt_close($query2);
} // end assignments array loop
echo' </tr>';
}
?>
</table>

Related

The first table row (dynamically generated) always shows, no matter the input value for Javascript

Sorry for asking, I am probably missing something small here but have no clue. I dynamically generated a long list of radio buttons using PHP. On top of the list is an HTML input to search through the list using jQuery. This works, except for one tiny detail. The first radio button in the list always shows, no matter what the search result is. Even if I type something completely different, I will always see the first radio button in the list together with the matching results.
What is going wrong here?
This is my dynamically generated list of radio buttons, using HTML and PHP:
<input id="addplantSearch" class="form-control" type="text" name="addplantsearch" placeholder="Zoek op (Latijnse) naam..." style="margin:0; height:48px;"> <!-- Search input -->
<?php
$query = "SELECT * FROM plants ORDER BY plants.name ASC;";
$post_data = $data->execute($query);
// Prepared statement in 'execute' method (Database class)
?>
<div class="addplant-list">
<?php
foreach ($post_data as $post) {
# Loop start
?>
<div class="searchable">
<label class="pselect-container"> <?php echo $post['name']; ?>
<input type="radio" name="selectPlant" value="<?php echo $post['plant_id']; ?>">
<span class="pselect-checkmark" style="width:100%;">
<img src="../system/src/img/plants/<?php echo $post['directory']; ?>/icon.png" />
<?php echo $post['name'] . " - (" . $post['name_latin'] . ")"; ?>
</span>
</label>
</div>
<?php
# Loop end
}
?>
</div>
And this is my jQuery, responsible for searching through the list:
$("#addplantSearch").keyup(function() {
var value = this.value;
$(".addplant-list").find(".searchable").each(function(index) {
if (!index) return;
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
});
EDIT: The first item in the list is determined by the alphabetical order (ASC) of my database results (see $query variable). So this is always the same item in alphabetical order.
It looks like your issue is with your if statement.
if (!index) return;
This problem occurs because JavaScript uses 0 based arrays, and 0 is also a falsy value. Meaning:
!0 === true
and the first item in the array will always return out of the function and won't be applicable to the toggle logic.
So probably a lot of ways to work around this, one would be to check the length of the array before the each function. Ex:
$("#addplantSearch").keyup(function() {
var value = this.value;
var searchableItems = $(".addplant-list").find(".searchable");
if (searchableItems.length) {
searchableItems.each(function(index) {
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
}
});

How can I display first 3 values from a foreach loop and on click more display All the Values from the row

I am looping through a list of values and there are more than 22 values. I want to just show maximum 3 values and a click more button so it can display all the values as the user request.
I am a little bit confuse on how to do that.
This is what I did before which when you click on the plus it will show all the records and when you click on the minus it will hide all the records
Do we have to limit the number values on the sql query or is there a PHP way to show three records and then using Javascript to display all?
Help a sister out ^^
<table>
<thead>
<tr>
<th>Std Id</th>
<th>List of Names</th>
</tr>
</thead>
<tbody>
<?php
foreach ($Names as $key => $name): ?>
<tr>
<td><?= $key ?></td>
<td class="collapse-control collapse-plus">
<?php
$students = [];
foreach($name as $r){
if(!in_array($r->getStudent(), $students ))
$students []=$r->getStudent();
?>
<span class="form-names d-none"><?= $row->getName()?><br> </span>
<?php } ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Script
$(document).ready(function() {
$('.collapse-control').on('click', function(e) {
var $cell = $(this).toggleClass('collapse-plus collapse-minus');
$cell.find('.form-names').toggleClass('d-none');
});
});
You can show all the data in PHP using loop (like what you did). Now, you just need to add a condition inside the loop. Tell the loop to show the first three items without any style or class of display:none, then the rest will have a class or style. The idea is like this:
$counter = 0;
foreach($name as $r)){ // your loop here
if($counter < 3){ //show the first 3 items
echo "<span class='form-names'>".$row->getName()."</span>";
}else{ //show the rest items but hide it
echo "<span class='form-names' style='display:none'>".$row->getName()."</span>";
}
$counter++;//add a counter
}
Then you can now trigger a button, when clicked, it will show all .form-names. OR you can use your existing JQuery toggle function.
No need to use array_slice, you just add a counter variable to check if the item is greater than 3. The use of this is to show the first 3 items as normal (no style of display:none), but the rest items will loop with style of display:none so it will hide on the webpage (but it is already loaded in DOM).

Javascript getElementsByName not working in PHP loop

I've the following PHP code :
//some code
$query = "SELECT * from store_00_transfers";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo "<tr><td align=center width=19%>{$row['item_no']}</td><td align=center><input type='text' value='{$row['qty']}' name='cqty[]' readonly ></td><td align=center><input type='number' min='0' name='nqty[]' onChange='check_not_large(this.value);' value='0'></td></tr>";
}
//rest of code
Now, as you can see there is a function inside onChange. That function is meant to check whether the number inserted by user for new qty should not exceed old qty (I use this method to transfer qty's from one store to another).
Please also note I've assigned a name cqty[] and nqty[] inside input fields.
I have javascript code :
<script>
function check_not_large(res) {
var old = document.getElementsByName("cqty[]");
var type= document.getElementsByName("nqty[]");
for(var i = 0; i < old.length; i++) {
if(type[i].value > old[i].value){
alert('Error : Qty Inserted should be Less than QTY found in Store !');
alert(type[i].value);
alert(old[i].value);
return type[i].value = 0;
}
}
}
</script>
I've used alert in javascript to test if correct values are collected and it seems that it works as needed, but NOT for validating if new qty is more than old qty, it seems that it works only for the first 4 rows then it stucks and starts validating the new qty in any row WITH the first old qty row .. I hope this makes sense to you.
Any alternative or suggestion will be appreciate it.
Thanks Guy
One problem with your code is that everytime you input value onto nqty and on onchange, the function check_not_large function gets called and it not only validating current row nqty and cqty values but also all the previous nqty and cqty row values.If your purpose is to check only if current row nqty value greater than cqty value, a much neater code will be to give some unique id value to each nqty and cqty elements.The code for the same can be optimized as given below.
PHP Code
$query = "SELECT * from store_00_transfers";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo "<tr>
<td align=center width=19%>{$row['item_no']}</td>
<td align=center>
//instead of name attribute you can give an id here and also assuming $row['item_no'] is unique
<input type='text' value='{$row['qty']}' id='cqty{$row['item_no']}' readonly >//assuming item_no is unique
</td>
<td align=center>
//instead of name attribute you can give an id here and also assuming $row['item_no'] is unique
<input type='number' min='0' id="nqty{$row['item_no']}" onChange='check_not_large({$row['item_no']});' value='0'>
</td>
</tr>";
}
Javascript Code
<script>
function check_not_large(item_no) {
var cqtvVal=document.getElementById("cqtv"+item_no).value;
var nqtvVal=document.getElementById("nqtv"+item_no).value;
//checking if typed value is greater than old value
if(nqtvVal>cqtvVal)
{
//write whatever code you want to do like give a warning message or make the nqtv value reset to zero etc
}
}
</script>

How do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.
The checkboxes look like:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid
The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.
The reason is it's displayed in a loop with output like this:
<tr>
<td><input type="checkbox" class="deletefunc" value="<? echo $mid; ?>"></td>
<td><input type="checkbox" class="star" value="1"> <!-- jquery/ajax onclick function --></td>
<td><a href></td>
<td><form name....><input type="submit" value="something"></form></td>
<tr>
So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....
And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.
I would do it like this:
HTML:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>
JS:
$(function() {
$('#delete-them').on('click', function() {
var data = $('.deletefunc').attr('name', 'delete[]').serialize();
$.ajax('delete-them.php', {
method: 'POST',
data: data,
success: function() {
alert('deleted!');
}
});
});
});
PHP:
<?php
$ids = $_POST['delete'];
$params = array_fill(0, count($ids), "?");
$sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
//DELETE FROM some_table WHERE id IN(?,?,?,?);
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
?>
So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.
We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.

How to get name by ID from other table

I have a table name "drug". It has column name "ingredians".
"ingredians" field has text (varchar)
I can select the "ingredians" using dropdown box.
<td width="100px"><center>
<select name="drugitem" style="width:100px; height:30px;" >
<? $sc="SELECT * FROM drug";
$scq=mysql_query($sc);
while($scf=mysql_fetch_array($scq))
{
?><option value='<? echo $scf[id];?>'><? echo $scf[ingredians];?></option>
<? } ;?>
</select></center>
</td>
And then I want to pass this "ingredians" both ID and VALUE to another table called "temp".
'temp' table has two colomns to catch these data called "drugitemid" and "drugitemname"
How can I pass both values.
Though your question is bit vague. As per my understanding what you need is to concat name with id in value for ingredients & than on other page you can use them after exploding with -,
<option value='<? echo $scf[ingredians].'-'.$scf[id];?>'><? echo $scf[ingredians];?></option>
On next page:
list($drugname, $drugid) = explode('-', $_POST['drugitem']);
Note: It's irrelevant to save both foreign id & name in any table.
You can use jquery. On this dropdown change event get value from.
var val_id = $("#yordropdown_id").val();
var name = $("#yordropdown_id option[value="+val_id+"]").text();
Then send ajax request with those id and names and save it to your temp table.
I think it makes sense!

Categories

Resources