How to get the value of entire dynamic row in PHP? - php

I have a table that is being populated by a given sql query, that has a radio button at the end.
How can i get the entire row value of a selected radio button passed to a different page?
results=mysqli_query($conn,$sqlitem);
while ($dat=mysqli_fetch_assoc($results)){
echo "<tr>";
echo "<td>".$dat['sellername']."</td>";
echo "<td>".$dat['itemname']."</td>";
echo "<td>".$dat['maker']."</td>";
echo "<td>".$dat['details']."</td>";
echo "<td>".$dat['condition']."</td>";
echo "<td>".$dat['price']."</td>";
echo "<td> <input type='radio' name='selc' width ='5px'> </td>";
echo "</tr>";
}
I have tried various combinations but for some reason the entire row value doesn't come. The last and closest option that I tried was this SOMETHING CLOSELY SIMILAR
I took the script portion and updated still isn't working. I believe there should be some solution for this.

You should probably use the MySQL primary key for each row, pass that info to the next page and have PHP perform a query for that item on the new page rather than explicitly passing content around from page to page.
That said, you can keep track of the order that you are echoing the keys in an array, then use that array to turn the row into an object:
var keys = ['sellername','itemname','maker','details','condition','price'];
$('input[type=radio]').on('change', function(event) {
if (this.checked) {
var $tr = $(this).closest('tr');
var $cells = $tr.find('td');
var obj = {};
$.each($cells, function(index, cell) {
obj[keys[index]] = cell.textContent;
});
console.log('row data', obj);
}
});
Note this is untested, but just demonstrates how you can match up an array of key names to the index their data can be found in a table cell

Related

PHP: How do I reference an element whose name I dynamically added using JQuery?

this is my second time asking for help here so I hope you don't mind if I make a mistake.
See I have a problem accessing an element (In this case, it's a < td >). I dynamically added it's name using JQuery as I 'echoed' it. I did this because the values inside the table it belongs to, are chosen by the user and is triggered by a button click.
Here's the JQuery:
$("#tblAddServices tbody").delegate("tr", "click", function(){
firstCellServ = $("td:first", this).text();
secondCellServ = $("td:eq(1)", this).text();
thirdCellServ = $("td:eq(2)", this).text();
fourthCellServ = $("td:eq(3)", this).text();
})
$('.service').on('click', function(e){
var $table = $("#tblServiceIncluded");
var newTR = $("<tr><td colspan=\"3\" name=\"servID[]\">"+firstCellServ+"</td>
<td colspan=\"3\">"+secondCellServ+"</td>
<td colspan=\"3\">"+thirdCellServ+"</td>
<td colspan=\"2\" class=\"sumService\">"+fourthCellServ+"</td>
</tr>");
$table.append(newTR);
});
Now, I have a PHP script that should be getting the value(s) of the first column of the table which I named 'servID[]'. I am using an array to get its values but I always end up with an Undefined Index warning for the 'servID'.
This is the PHP script:
<?php
if(isset($_POST['btnSavePack']))
{
$serviceArray = array();
foreach($_POST['servID'] as $serviceKey){
$serviceArray[] = $serviceKey;
}
foreach($serviceArray as $result) {
echo $result, '<br>';
}
}
?>
I hope you someone could help me figure out a way to make this work. I know I could do this with Ajax but I prefer this method since I am only a beginner. Thank you.
You can put the value in an input box with a type hidden.
"<td colspan=\"3\"><input name=\"servID[]\" type=\"hidden\" value=\""+firstCellServ+"\"/>"+firstCellServ+"</td>"

JQuery specific variable from a php printed table

Ive got a table with buttons:
and Ive set specific ID's to each one but I dont see how I can access them all from a JQuery script so i can set a specific get to each one of them.
Edit:
All of the buttons have unique ids:
Shown in google chrome inspect element :
When I click REMOVE i want the row to get removed. I can do this and have done this with PHP via GET however I dont want to have to refresh the page every time I remove one. I tested doing it with JQuery .GET and it works fine however I dont want to have to make a new script to have to delete every single row, rather do it dynamically by getting the ID of the row and removing the row that the REMOVE button is in. Ive tried multiple ways of doing this but all I do is fail.
This is the script that prints the data in the table
function print_data($info1,$info2,$info3,$info4,$info5,$info6,$info7,$info8){
echo"<tr><td id='notice1id$info8'>$info1</td><td id='noticename$info8'>$info2</td><td id='noticetype$info8'>$info3</td><td id='noticecontent$info8'>$info4</td><td id='noticeshow$info8'>$info5</td><td id='noticeedit$info8'><a href='admincp.php?edit=1&editid=$info6'><div class='btn btn-success'>Edit</div></a></td><td id='noticeremove$info8'><input type='button' id='remove$info8' value='remove' onclick='removeMe();' class='btn btn-danger' name='$info8'></td><td style='display:none;'><p id='getid' name='$info8' style='display:none;'></p></td><td style='display:none;'><script> function removeMe() { alert($info8);}</script></td><input id='noticeid$info7' class='form-control' style='display:none;' type='text' name='$info8' value=$info7></td></tr>";
?><?php
}
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
print_data($row['NoticeID'],$row['NoticeName'],$row['NoticeType'],$row['NoticeContent'],$row['NoticeShow'],$row['NoticeID'],$row['NoticeID'],$row['NoticeID']);
}
JavaScript:
$(document).ready(function () {
var id = $("#getid").attr("name");
alert("#remove" + id);
$("#remove" + id).click(function () {
var getcontent = $("#noticeid4").val();
$("#notice1id5,#noticename5,#noticetype5,#noticecontent5,#noticeshow5,#noticeedit5,#noticeremove5").slideUp(300, function () {
// Animation complete.
});
});
});

Php while loop with js variables

The plan:
Basically I have a set of clothing items stored in a table each containing "item_name" "item_id" and "item_shortcode" I want to have a link per clothing item, when the user clicks the link the item needs to be added to an array (the selected array)
I'm trying to create a javascript object based off the data I've gathered from the mySQL database, then pass that data to a function when a div is clicked to my method.
this is an example:
<?php
while($row = mysql_fetch_array($results)){
?>
<script>
var item = new Object();
item.itemName = <?php echo json_encode($row['item_name']); ?>;
</script>
<?php
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(item);\">";
//echo $row['item_name'];
echo "</div>";
}
}
?>
EDIT: this is just an example I'll be populating my object with lots of data, not just item_name
problem is the last object seems to be assigned to every div in while loop.
Anyone point out where I am going wrong?
Well, i honestly don't know if i really got you, but if i see it right, then you simply overwrite the item-object in every run of the while-loop.
After the last loop (after this comes the output) the variable "item" is set to the last result of the loop, so clicking on any div will return "item" - the last item of the loop.
As a solution, try to save the rows name in the div as a parameter, like
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(\'".$row['item_name']."\');\">";
You're redefining item on every iteration. Why not do something like this:
As per edit, you can create an item array and populate it in the loop:
<script type="text/javascript">
var objects = new Array();
</script>
<?php while($row = mysql_fetch_array($results)): ?>
<script type="text/javascript">
var item = new Object();
item.itemName = '<?php echo json_encode($row['item_name']); ?>';
objects.push(item);
</script>
<div id="<?php echo $row['item_id']; ?>" class="choice">
<?php echo $row['item_name']; ?>
</div>
<?php endwhile; ?>
then in js OUTSIDE of your loop:
$('.choice').on('click', function(){
SetSelectedChoice($(this).html());
});
function SetSelectedChoice(name)
{
for(var i = 0; i < objects.length; i ++)
{
if(objects[i].itemName == name)
{
//do something
}
}
}
NOTE: I wouldn't really recommend this kind of weird loop for comparing names. I just don't know what else you are doing with passing the name to this function. I would pass the item id or the index value and directly access an item in the array instead of a loop. Make sense?
Basically, stop using onclick. The whole world is leaning more on listeners. Secondly, no need to create an object at all. You don't seem to be using it and even if you did, you didn't put single quotes around the name like you should for strings. Thirdly, please break out of php to write html. It's just cleaner and easier. Morely, assign the item's id to the id parameter. It gets really ugly to have names and spaces in the ids of elements. And you don't really seem to need one since you don't use it in your example. None the less, I put it in there in case you wanted to access it like $(this).attr('id') in the on click listener.
But if I missed the point, perhaps you can clarify and I may update to better fit your needs

how to get information from a field that is in a loop using javascript

I have a bunch of image names that is being retrieved from my data base and is in a while loop. In this loop I have a small form with the image names. This form is being use for another purpose. what I want is to get the field information with the item name to a javascript.
Example :
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "< input type='hidden' name='$itemname' value='$itemname'>
<img src='source' onclick='getname()' width='100%' height='100%' />";
}
I believe the reason why every image I click on is only giving me the first information from the database is because my id is being duplicated. My question is how can I get the field information to javascript without using the getElementById?
Use the following altered PHP:
$i = 0;
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "<input type='hidden' name='".$itemname."[]' id='input$i' value='$itemname' />";
echo "<img src='source' onclick=\"getname('input$i')\" width='100%' height='100%' />";
$i++;
}
Then you can retrieve the input value in Javascript:
function getname(id) {
var theinput = $('#'+id).val(); // jQuery example
// do something
(I also changed the input name to be an array, of couse you could name it what you want, maybe $itemname$i could be an idea, it depends how and if you want to process your form, however the name should be unique or array for good practice)
Here is a working example of HTML/JS: http://jsfiddle.net/fuHSv/1/
How about using some jQuery 1.8.2 like the following:
$(document).ready(function() {
var inputs = $('input').on('click', function() {
var name = $(this).attr('name');
var val = $(this).val();
// do stuff
});
});
See api.jquery.com for more.

How to access the value of an element detected by livequery

I am using $_SESSION to pass back a value in the event of page redirect.
As jquery cannot access $_SESSION I decided to use PHP to output the value to a hidden div and remove that div once the value had been picked up. I expect that there is a neater way to do this but I don't know how else to expose the $_SESSION variable to jquery.
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
?>
<?php
if (count($pass_Back) != 0){
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\" value=\"" . array_shift($pass_Back) . "\"/><br />";
echo "<div id=\"pass_Back\" style=\"visibilty: hidden;\" ></div>";
} else {
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\"/><br />";
}
?>
Once this was done I needed a method to let jquery know if and when this new element was added to the DOM. Hence I used the plugin livequery to match when the element added. This it does which is great.
But when I try to access the value in the div it states that it is undefined.
$("#pass_Back").livequery(function(){
if ($("#class_Name").val() != 0){
var class_Name = $("#class_Name").val();
get_Schedule_Data(class_Name);
} else {
var class_Name = "ALL";
get_Schedule_Data(class_Name);
}
$value = $(this).attr("value");
auto_Fill_Schedule($("#pass_Back").attr("value"));
// destroy pass back
$("#pass_Back").remove();
});
When reviewed in firebug I note that at the point that livequery finds the added element no html is displayed. The DOM is ready otherwise the livequery couldn't have functioned but is this why no value is found?
Any guideance gratefully received.
Don't use this:
$value = $(this).attr("value");
Do the following to get a value (for inputs in most of cases):
(assuming $(this) is your input)
$value = $(this).val();
For div cases, there is no value, but you can get the html or text from inside as the value:
(assuming $(this) is your div)
$value = $(this).html();
//or:
$value = $(this).text();
Just to know...
You can mix PHP with jQuery but take a look at my answer from this post for better understanding:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
As long you're not outputting the entire $_SESSION array, or anything of importance, you're going to be ok:
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
if (count($pass_Back) != 0){
echo '<div id="passBack" type="text" value="'.implode(",", array_shift($pass_Back)).'" />';
}
?>
JS
$(function() {
if ($("#passBack").length) {
//element exists in DOM, get the value
var passBack_data = this.value;
//do something with the value
}
});
Just output the element and make sure it's a string, not an array ( I used implode() ), and on pageload see if it exists (has length), and get the value.

Categories