Get the value from many radiobuttons inside a table - php

First I create a table with n number of rows and each one of them contains two radio buttons. I need to get all the id from the table row selected and the option selected. I mean if the user selected yes or no.
<table border='1' style='width:100%'>
<tr>
<th>Date</th>
<th>Time</th>
<th>Confirm Order?</th>
</tr>
<tr id='56'>
<td>".$date." </td>
<td>".time." </td>
<td>".$prog." </td>
<td>
<input type='radio' name='prog1' />NO
<input type='radio' name='prog1' />SI</td>
</tr>
</table>
Now what I got so far is getting the ids from the rows checked. Like this:
var idss = [];
$(':radio:checked').each(function(index) {
var closestTr = $(this).closest('tr').attr('id');
idss.push($(this).closest('tr').attr('id'));
});
$(function test() {
$.ajax({
type: 'POST',
url: 'test.php',
data: {
idss: idss
}
});
How can I get an array with all ids where 'no' was selected, and one array with all the ids where 'yes' was selected.

I made a fiddle here: https://jsfiddle.net/7w2df640/
This is the js:
function getArray(){
ar = {};
$(".datarow").each(function(i,o){
ar[$(o).attr("id")] = $(o).find("input[type='radio']:checked").val()
});
console.log(ar);
}
For the html, you have to add a class to the rows:
<tr class="datarow" id='56'>
and also add a value to the radio:
<input type='radio' name='prog1' checked value="no" />
In the end you will get an array exactly as you wanted:
Object {56: "si", 57: "no"}
Does that make sense?

Related

Looping through serialized data to insert updates to MySQL DB

Thanks to the help below, I switched my code to use serlize(), but I am still having a similar problem of only getting the latest row sent, here is what I am doing now
<form id="test_table">
<table>
<thead>
<tr>
<th> ID </th>
<th> col2 </th>
<th> col3 </th>
</tr>
</thead>
<tbody><!--table body-->
<form id="form_x">
<tr>
<td> <input type="text" name="col1" default value="1"> </td>
<td> <input type="text" name="col2" default value="cat"> </td>
<td> <input type="text" name="col3" default value="dog"> </td>
</tr>
<tr>
<td> <input type="text" name="col1" default value="2"> </td>
<td> <input type="text" name="col2" default value="fish"> </td>
<td> <input type="text" name="col3" default value="rabbit"> </td>
</tr>
</tbody>
</table>
</form>
<button class="btn btn-primary" value="test_table" onclick="update(this.value)">Update</button>
<p><tt id="results"></tt></p>
<script>
function update(form_name){
var str = $( test_table ).serialize();
$( "#results" ).text( str );
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data: $( "#"+form_name ).serialize(),
success : function(res){ console.log(res); }
});
}
</script>
I can see the serialized data being captured i.e.,
col1=1&col2=cat&col3=dog&col1=2&col2=fish&col3=rabbit
But when I dump what is being passed, it is only seeing the last row value
update.php
<?php var_dump($_POST); ?>
Result:
array(3) {
["col1"]=>
string(1) "2"
["col2"]=>
string(4) "fish"
["col3"]=>
string(6) "rabbit"
}
Can anyone direct me to some advice to fix my update.php page to loop through the POST data? I want to update the database row from each id of that row e.g.
//setup loop
$sql = "UPDATE Table SET
col2 ='".$_POST["col2"]."',
col3 ='".$_POST["col2"]."',
WHERE id='".$_POST["col1"]."' ";
i.e.,
$sql = "UPDATE table SET
col2='cat' , col3='dog'
WHERE id=1";
$sql = "UPDATE table SET
col2='fish' , col3='rabbit'
WHERE id=2";
===========================================================================
Old Question:
I am trying to enable a user to edit a dynamically created row (with user based inputs in TDs) that send and update on click of an update button, I can see the inputs are being captured correctly, but cannot work out how to update the database from the ajax call, here's the (abridged) code:
form_page.php
<table id="table_name">
<thead>
<tr>
<th>ID</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
The phpcode associated with generating the table rows:
<?php
echo '<form id="" method="POST" action="" >';
$sql= "SELECT * FROM tablename";
$stmt= $conn->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row) {
echo '<td>';
echo 'ItemID_'.$row['ID'].'';
echo '</td>';
echo '<td>';
echo ' <input class="update_value" type="text" id="ItemID_'.$row['ID'].'" default value="'.$row['col2'].'">';
echo '</td>';
echo ' <input class="update_value" type="text" id="ItemID_'.$row['ID'].'" default value="'.$row['col3'].'">';
echo '</td>';
echo'</tr'>;
}
?>
<button type="button" id="update_button">Update</button>
</form>
</table>
Result with editable col 2/3:
ID | col2 | col3
1 | lorem (editable) | ipsum (editable)
2 | dolor (editable) | sit amet (editable)
Update (Button)
With the code looking something like:
<table id="table_name">
<thead>
<tr>
<th>ID</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<form id="" method="POST" action="">
<tr>
<td>
ItemID_1
</td>
<td> <input class="update_value" type="text" id="ItemID_1" default value="lorem">
</td>
<td> <input class="update_value" type="text" id="ItemID_2" default value="ipsum">
</td>
</tr>
</tbody>
<button type="button" id="update_button">Update</button>
Here's the ajax I am using to send it to the update page
<script>
$(document).ready(function(){
$("#update_button").click(function(e) {
e.preventDefault();
var values = {};
$('input.update_value').each(function(n, user_input){
values[ $(user_input).attr('id') ] = $(user_input).val();
//used to test and make sure its passing id vals to values
//alert(JSON.stringify(values, null, 4));
});
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data: { updatefrominputs: values }
});
});
});
</script>
With the alert above (used for testing) showing:
localhost says
{
"ItemID_1": "lorem"
"ItemID_1": "ipsum"
}
OK so far, but then on another click it over writes the "lorem"
localhost says
{
"ItemID_1": "ipsum"
"ItemID_2": "dolor"
}
This is the first problem, it has over written the "lorem" value to send across
Here is the second problem and where I am currently stuck, sending and updating the database
I can see that the ajax is being posted by adding this to the ajax:
success: function (data) {
alert("sent");
}
The update.php file code:
<? php
include connect.php //database connection script (don't think I need to call it)
foreach($_POST['updatefrominputs'] as $id=>$value)
$sqlQuery = "UPDATE tablename SET
//col2=col2inputvalue
//col3=col3inputvalue
WHERE
//col1id=the NUMBER without the ID_part?
";
$sqlQueryStmt = $conn->prepare($sqlQuery);
$sqlQueryStmt->execute();
?>
The problem I have is that I cannot seem to get it to update the database, I am not sure on how to fill out the UPDATE clause below. Also, it doesn't even feel like it posts to this page, but the success function says it does??
Also, how would I just get the number to use in the WHERE clause? I can edit the code above to just give me the ID number and then use col1ID=col1passedID but I would end up with duplicate ID's if I use this process across more than one form (on the same page). e.g.
<form 1>
foreach ($results1 as $row1) {
echo ' <input class="update_value" type="text" id="'.$row1['ID'].'" default value="'.$row['col2'].'">';
}
</form 1>
<form 2>
foreach ($results2 as $row2) {
echo ' <input class="update_value" type="text" id="'.$row2['ID'].'" default value="'.$row2['col2'].'">';
}
</form 2>
Would output:
<form 1>
<input class="update_value" type="text" id="1" default value="lorem">
</form 1>
<form 2>
<input class="update_value" type="text" id="1" default value="ipsum">
</form 2>
One solution I can think of would be to send the ajax like this:
var updatedetals= {
id: $("#ItemID_1").val(),
col1: $("#col2").val(),
col2: $("#col2").val()
}
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data:updatedetals,
dataType: 'JSON',
success: function(JSON){
refreshResults();
}
});
But this won't give me unique IDs either, and I would have to do a ajax call for every row?
Is there a better way to iterate over every uniquely generated row, get the TD input values and send those updated values to the database?
You need to use name="col1[]" in your html this would send all values in an array. Because you have multiple inputs with the same name php by default gets the last one. if you add [] you can fetch values like $_POST["col1"][0] and such.
Then you can also loop over the values like
for($i=0;$i<count($_POST["col1"]);$i++){
$col1 = $_POST["col1"][$i];
$col2 = $_POST["col2"][$i];
$col3 = $_POST["col3"][$i];
//use the variables in update query
}
The problem is that your columns have duplicate names but $POST requires unique keys for values. So you get 3 keys only: col1, col2, and col3... and the values get overwritten, so you're left with only the last row's values.
If you want to collect all the rows, then you should give each a unique name. E.g.
<form id="test_table">
<table>
<thead>
<tr>
<th> ID </th>
<th> col2 </th>
<th> col3 </th>
</tr>
</thead>
<tbody><!--table body-->
<form id="form_x">
<tr>
<td> <input type="text" name="row1_col1" default value="1"> </td>
<td> <input type="text" name="row1_col2" default value="cat"> </td>
<td> <input type="text" name="row1_col3" default value="dog"> </td>
</tr>
<tr>
<td> <input type="text" name="row2_col1" default value="2"> </td>
<td> <input type="text" name="row2_col2" default value="fish"> </td>
<td> <input type="text" name="row2_col3" default value="rabbit"> </td>
</tr>
</tbody>
</table>
</form>
<button class="btn btn-primary" value="test_table" onclick="update(this.value)">Update</button>
<p><tt id="results"></tt></p>
<script>
function update(form_name){
var str = $( test_table ).serialize();
$( "#results" ).text( str );
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data: $( "#"+form_name ).serialize(),
success : function(res){ console.log(res); }
});
}
</script>
Try it. This will give you six values in your php $POST.
Then you can iterate over them and extract the col name using some string slicing techniques, like split or substr.

PHP - HTML best practices to handle (submit) generated rows

I have html table generated via ajax. And last column on this table contains button. My question is what is the best practice to submit these rows (only one at time. I need use this method to amend records).
Is it worth to wrap each row with
<form>
<input type="hidden" value="hidden value">
<input type="submit">
</form>
Or people using something difference? Reason why i'm asking for is because i'm worry about very long list example 1k rows or 10k rows (that means i will have 1k or 10k forms on a page).
You can just use a hyperlink (which you can style to look like a button using CSS if you want). e.g:
Edit
where the value you give as the "id" parameter is the primary key of the record in that row.
Then in edit.php look for the id value using $_GET["id"] and fetch the appropriate record from the DB.
As Progrock advises, a form element may only be used "where flow content is expected" (i.e. not as a direct child of table or tr).
HTML 5 introduces a form attribute as a workaround:
<form id="row_1">
<input type="hidden" name="id" value="pk1">
</form>
<form id="row_2">
<input type="hidden" name="id" value="pk2">
</form>
<table>
<tr>
<td> <input type="text" name="attribute1" form="row_1"> </td>
<td> <input type="submit" form="row_1"> </td>
</tr>
<!-- and so on for each row -->
</table>
It has been brought to my attention that in this case, there is no direct user input being submitted, but only generated contents.
Well, then the solution is even simpler:
<table>
<tr> <td>
<form id="row_1">
<input type="hidden" name="id" value="pk1">
<input type="hidden" name="attribute1" value="whatever">
<input type="submit">
</form>
</td> </tr>
<!-- and so on for each row -->
</table>
I thought I'd have a go without form elements, working with editable table cells. Within each row you provide a button. And when you click it, an ajax post is made of the cell values.
You could have a non js fall back where the save button is replaced for an edit button that takes you to another page with a single form.
Forgive my JS.
I have the session storage in there just to check the concept.
<?php
session_start();
var_dump($_SESSION);
$data = array(
23 => ['triangle', 'green', '2'],
47 => ['square', 'red', '3'],
17 => ['pentagon', 'pink', '4']
);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Save state here
$_SESSION['submission'] = $_POST;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
$('button').click(function() {
// Get all table cells in the buttons row
var $cells = $(this).closest('tr').find('td[contenteditable="true"]');
var jsonData = {};
$.each($cells, function() {
jsonData[get_table_cell_column_class($(this))] = $(this).text().trim();
});
jsonData['id'] = $(this).attr('id');
$.post('',jsonData, function() {
alert('Saved.');
});
});
function get_table_cell_column_class($td)
{
var $th = $td.closest('table').find('th').eq($td.index());
return $th.attr('class');
}
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th class="shape">Shape</th>
<th class="colour">Colour</th>
<th class="width">Width</th>
<th>Ops</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $row) { ?>
<tr>
<?php foreach($row as $field) { ?>
<td contenteditable=true>
<?php echo $field ?>
</td>
<?php } ?>
<td>
<button id="<?php echo $key ?>">Save</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
You can use the following
<table id="YourTableId">
...
<tr data-id="yourrowId">
<td class="col1"> value1</td>
<td class="col2"> value2</td>
<td class="col3"> value3</td>
<td class="actions">
Submit
</td>
</tr>
....
</table>
your javascript code will be like
$(document).ready(function (){
$('#YourTableId a').off('click').on('click',function(e){
e.preventDefault();
var tr = $(this).closest('tr')
var data={ // here you can add as much as you want from variables
'id' : tr.data('id), // if you want to send id value
'col1': tr.find('.col1').text(),
'col2': tr.find('.col2').text(),
'col3': tr.find('.col3').text(),
};
$.ajax({
method: 'post',
url: 'your url goes here',
data: data,
success: function(result){
// handle the result here
}
});
});
});
Hope this will help you

How to Delete multiple rows from a datatable [duplicate]

This question already has answers here:
Delete multiple rows by selecting checkboxes using PHP
(6 answers)
Closed 8 years ago.
I have the following html code of datatable rows which are dynamically generated using php
<tr>
<td><input type='checkbox' name='post[]' value="1"></td>
<td>21-Apr-2014</td>
<td>TEST</td>
<td>merchant.inloc8.com</td>
<td>coupon</td>
<td>mmmq.com/id/rt7WLskQq2lLlO2kTN</td>
<td>abc.com/response.php (default)</td>
<!--<td align='center' width='30'><a data-toggle='modal' href='#' ><i class='icon-remove text-danger'></i></a></td> -->
</tr>
<tr>
<td><input type='checkbox' name='post[]' value="2"></td>
<td>21-Apr-2014</td>
<td>say nw</td>
<td>abcdefg.com</td>
<td>abc</td>
<td>mmmq.com/id/lbruxjFl6PitP25vTN</td>
<td>abc.com/response.php (default)</td>
<!--<td align='center' width='30'><a data-toggle='modal' href='#' ><i class='icon-remove text-danger'></i></a></td> -->
</tr>
When a checkbox is selected,I wanted to identify the row and delete that row in the backend.I think this can be done using ajax.But no idea.please help
See this example
Checkboxes.
<input type="checkbox" value="1" name="letter[]" />
<input type="checkbox" value="2" name="letter[]" />
<input type="checkbox" value="3" name="letter[]" />
<input type="button" id="btn_" value="submit" />
When the button is clicked you can get the values of the selected checkboxes as an array and pass it to the ajax call,
$("#btn_").on('click', function () {
arr=[];
var arr = $("input[name='letter[]']:checked").map(function() {
return this.value;
}).get();
$.ajax({
type: "POST",
data: {arr:arr},
url: "action.php",
success: function(msg){
alert("success");
}
});
});
You will get the values in action.php and delete the rows there. You can change the alert("success");to the callback you want to get.
serialize form data , pass to controller , delete entries.
full outline here
Look, I'm giving you the logic only. If I give the code, you will not learn anything.
Well, set the checkbox value to the $id of the Table, and once you click submit, check all $ids which are checked, and run a loop to delete the $ids with a query.

populate values of a row from the id selected

I'm using PHP to populate names into an option list based on values from a database.
Once a name is selected I want to populate the values of a row based on whatever name has been selected.
I had no problem populating the option list with the name values, but once I select a name the records of that row will not display in the input boxes.
Here is the code I'm working with:
$query = "SELECT name, id
FROM artists
ORDER BY name";
$mysql_stuff = mysql_query($query, $mysql_link);
while($row = mysql_fetch_row($mysql_stuff)) {
$artists_name = htmlspecialchars(stripslashes($row[0]));
$artists_id = stripslashes($row[1]);
// we compare the id of the record returned and the one we have selected
if ($artists_id) {
$selected = $artists_id;
} else {
$selected = "";
}
print("<option value=\"$artists_id\">$artists_name</option>
");
}
print("</select>
<input type=\"Submit\" name=\"submit\" value=\"Update\">
<input type=\"Submit\" name=\"delete\" value=\"Delete\">
<br >
<br />
Edit Biography:
</td>
</tr>
");
if (isset($_POST['submit'])) {
print("<tr valign=\"top\">
<td valign=\"top\" width=\"150\">Name</td>
<td valign=\"top\">Artist Biography</td>
</tr>
");
print("<tr valign=\"top\" bgcolor=\"$colour\">
<td valign=\"top\">
<input type=\"text\" name=\"artists_name[$selected]\" value=\"$artists_name\" size=\"40\" />
</td>
<td valign=\"top\">
<textarea name=\"artists_Biography[$selected]\" cols=\"40\" rows=\"10\">$artists_Biography</textarea>
</td>
</tr>
");
}
print("</table>
</form>
");
Can I please get some assistance with populating the values of the selected name into the input boxes.
So your submitting artist ID to the post. The post would then refresh or change the page. Assuming the action is that page you have the ID in your post. How do you get Artist Name from the ID? Do you run another sql query on the id to find the name? Might need some clarification on the order of your code to help. Thanks
I'm not sure how to interpret this code. Use Ajax. Use Jquery on change() method to take the value of the select and send it via ajax() to a php script that gets the info from the DB and returns what you want. Then use the Success part of the .ajax() method to put that data into you input on the form.
$(function(){
$("select#artist").change(function()
{
var artist = $("select#artist").val();
$.ajax({
type: "POST",
url: "ajax-find-artist.php",
data: "artistID=" + artist,
cache: false,
success: function(html){
var newElems = html;
$("input#artistRestult").html(newElems);
}
});
});
});

how to update and post the value of checkbox from ajax call

i retrieved data from mysql table into html page i.e
$query="select * from student";
$result=mysql_query($query)or die(mysql_error());
while($rs=mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $rs['st_id']; ?></td>
<td align="center"><?php echo $rs['name']"; ?></td>
<td align="center"><input type="checkbox" name="checked[]" <?php if($rs['checked']==1){echo "checked"; } ?> /></td>
<td align="center"><img src="images/delete_icon.png" alt="Delete" /></td>
<td align="center"><img src="images/update.png" alt="Update" /></td>
this is gives me the output
assume that checkbox of id 1 is checked and retrieved from mysql table.
Now what i want to do is that when i checked the remaing two checkbox into this table and a function is called to ajax which goes to php page and update the value of checked field according to the given id (i.e 2 and 3 in this case). Not refreshing the whole page nor updating the whole record just the value of check box. i am new to ajax so
any help would be greatly appreciated.
Yes, exploring jqGrid isn't a waste of time at all. However, since you want to update only on change of checkbox value. Here's what you can do..
<input type="checkbox" name="check1" />
And..
$().ready(function(){
var st_id = <?php echo $rs['st_id']; ?>;
//Or you could use a hidden field in the form
$(':checkbox').click(function(){
var chkName = $(this).attr('name');
var checkVal = $(':checkbox[name='+chkName+']').attr('checked');//true or false
$.ajax({
url: 'MyApp/update.php?checboxName=' + checkVal,//Do update on server-side
success: function(data) {
alert('Updated successful.');
}
});
});
});
Also, you can do a $('formID').serialize() wihch returns name=value pairs of all form elements that can then be appended in the call to your php script.

Categories