reload multiple table cells with jQuery - php

I have many forms in a page, each form with several inputs. When you click Submit on a form (say Form0), inputs are send to Reassign.php,that perform a search in a DB according to user inputs, and then a cell with div id="Cell0" in a table of the page is reloaded with data echoed by Reassign.php.
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var MyVariables = $(this).serialize();
$('#Cell00').load('Reassign.php?MyVariables=' + MyVariables);
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var MyVariables = $(this).serialize();
$('#Cell10').load('Reassign.php?MyVariables=' + MyVariables);
return false;
});
});
</script>
A stripped down version of the table:
<table>
<tr>
<td><div id="Cell00"><img src="Image0.jpg"/></div></td>
<td><div id="Cell01">Text1</div></td>
<td><div id="Cell02">Price1</div></td>
<td><div>
<form name="Form0" id="Form0">
<input type="hidden" name="Qst" value="0">
<input type="image" src="ReloadRed.gif" alt="Submit"/>
<select name="cmb1"><option>cmb1Option1</option><option>cmb1Option2</option></select>
<select name="cmb2"><option>cmb2Option1</option><option>cmb2Option1</option></select>
</form>
</div>
</td>
</tr>
<tr>
<td><div id="Cell10"><img src="Image0.jpg"/></div></td>
<td><div id="Cell11">Text1</div></td>
<td><div id="Cell12">Price1</div></td>
<td><div>
<form name="Form1" id="Form1">
<input type="hidden" name="Qst" value="0">
<input type="image" src="ReloadRed.gif" alt="Submit"/>
<select name="cmb1"><option>cmb1Option1</option><option>cmb1Option2</option></select>
<select name="cmb2"><option>cmb2Option1</option><option>cmb2Option1</option></select>
</form>
</div>
</td>
</tr>
</table>
A sample Reassign.php:
<?php
session_start();
$MyVariables = $_GET['MyVariables '];
$cmb1 = $_GET['cmb1'];
$cmb2 = $_GET['cmb2'];
$cmb3 = $_GET['cmb3'];
parse_str($MyVariables);
$Preg=$MyVariables;
$link = mysql_connect("localhost", usr, pswrd) or die(mysql_error());
#mysql_select_db("MyDB") or die( "Unable to select database");
mysql_query ("SET NAMES 'utf8'");
$query = "SELECT Img FROM MyTable WHERE Column1=$cmb1 AND Column2=cmb2";
if($success = mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$image="../ImageFolder/".$row[0].".png";
}
}
echo "<img src=\"".$image."\" />";
?>
This is OK.
Now I want other cells in the table to change as well, but with different (and related) data. Indeed, in the DB seach by Reassign.php, $row[0] is echoed (and thus loaded) in Cell00, and I want $row[1] to be send to Cell01, $row[2] to Cell02 and so on.
My problem is that right now I'm loading Cell0 echoing their content. I think i could do the job calling different php (Reassign0.php to echo data to Cell00, Reassign1.php to echo data to Cell01) but seems rather odd. Any ideas?

Here is a better approach... You can echo JSON instead of HTML from you PHP script, with all fields of the row. (Other code must be put in place for this to work for you, I'll let you research it on your own)
echo json_encode($row);
In your JS, get that json with $.getJSON(url, callback) or $.get(url, callback) depending on your server configuration
Then, loop through the cells and inject the data in your callback
$.getJSON('Reassign.php?MyVariables='+MyVariables, function(row){
for(i=0;i<row.length;i++){
$("#Cell0"+i).html(row[i]);
}
});
EDIT: if you data is not already formatted as HTML (like for images), be sure to do it in your callback. For example, if the first element is always an image URL and the rest is plain data, you can do :
$.getJSON('Reassign.php?MyVariables='+MyVariables, function(row){
for(i=0;i<row.length;i++){
var content = ( i == 0 ) ? '<img src="'+row[i]+'" alt="" />' : row[i];
$("#Cell0"+i).html(content);
}
});

Related

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

getting mysql data from several unique text inputs without creating multiple connection scripts?

I have an HTML table which has text inputs for each row, depending on the table in question, there could be anywhere from five to five hundred unique text inputs which need to store their inputs separately, so they can be called and displayed on that same row.
With my current database connection script, and HTML set up the way it is, all the inputs will be stored in the same table with no way to differentiate between one set of data or another.
What solution to this problem would work, short of having to create a seperate and unique script for every single input?
$(document).ready(function() {
$(".toggler").click(function(e) {
e.preventDefault();
$('.cat' + $(this).attr('data-prod-cat')).toggle();
});
});
$('.submit').click(function(e){
e.preventDefault();
var me = $(this);
$.ajax({
type:"post",
data: {price : me.closest('.input').val()},
url: "link/to/your/mysql/function/"
}).done(function(html){
alert(success);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table>
<tr>
<td>Product</td>
<td>Price</td>
<td>Destination</td>
<td>Updated on</td>
</tr>
<tr>
<td>Oranges</td>
<td>100</td>
<td>
<button class="toggler" data-prod-cat="1">+ On Store</button>
</td>
<td>22/10</td>
</tr>
<tr class="cat1" style="display:none">
<td style="white-space: nowrap">Enter Amount:
<input type="text" maxlength="4" name="quantity" class="input" /> Submit
</td>
</tr>
<tr>
<td>Apples</td>
<td>100</td>
<td>
<button class="toggler" data-prod-cat="2">+ On Store</button>
</td>
<td>22/10</td>
</tr>
<tr class="cat2" style="display:none">
<td style="white-space: nowrap">Enter Amount:
<input type="text" maxlength="4" name="quantity" class="input" /> Submit
</td>
</tr>
</table>
<html>
<body>
<?php
$con = mysql_connect("mysql_url","id","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database_name", $con);
$var = $_POST[price];
$sql="INSERT INTO table (price)
VALUES
('$var')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
If I understand your question correctly, you want to be able to enter new data without having to run a separate command for every single entry.
I also see you have a separate submit button for every field, which can be unwise.
You can try two things right now:
1) Make a global Submit button that counts for the entire table. You can use a foreach() loop in PHP to pick up the separate values and build a single SQL command like this:
$sql = "INSERT INTO table VALUES(price) VALUES";
$ran_once = false;
foreach($_POST as $p) {
if($ran_once) {$sql .= ", ";}
else {$sql .= "('$p')";}
$ran_once = true;
}
$sql .= ";";
2)You can use jquery to send the data dynamically for every 'submit' button you click. This can be done with the $.post( [address], {[data]}, [success]) function.
side note: I see a lot of people still use mysql_* instead of mysqli_*. I've used both and I think mysqli_* is much easier then mysql_* (in php)
You can use inline data attributes. When you generate the page add this to every submit button:
data-cat="id-of-cat-goes-here"
This way you can keep track which button is for which category.
You can access the values with jQuery easily. The code below will give you the ID of the category that the button relates to (assuming this is when you click on the button).
$(this).data('cat');
More information on how to use data attributes: MDN - data attributes.

sending checked box values to php script to process via jquery

I have a table with four columns with a checkbox at the end of each row. I would like to know if there is a way of writing a jquery function that will select all the values of each row when the check box has been ticked and the submit button has been clicked.. and then pass the values to .php file to process/display. The reason i want to use the .php file is because i want to run a query to show all registered users on my system and then send the checked rows (id and name) to those users.
Sounds very complicated but i really need some help. thanks in advance.
here is the html code:
<div class="valuesOfObs">
<table>
<thead><tr><th>Valuation Name</th><th>Valuation Goal</th><th>Valuation Description</th><th>Options</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM valuation';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ValuationID'].'">';
echo '<td class="crsDesc">'.$row['ValuationName'].'</td>
<td >'.$row['ValuationGoal'].'</td>
<td >'.$row['ValuationDescription'].'</td>
<td ><a href =values.php?action=invite&id=aValue> xValue </a></td>
<td > <input type="checkbox" name="selectValue">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
<input type="button" name="addrow" id="addrow" value="Add row">
<input type="button" name="inviteObs" id="inviteObs" value="Invite Obstacle";>
Here is what I have written for the jquery so far.. I am trying to spilt the values so i can choose specifically which ones to process and then later on user the .join() method. Please help out if on the wrong track
$("input[type=checkbox], input[type=button]").on("click", function () {
$( ":checked" ).map(function() {
return $(this).closest("tr").text();
}).split("</td><td>");
var compName = $("#id").val();
$.ajax({
url : "inviteObstacles.php",
type : "POST",
data : {"compID" : compName},
success : function (n){
//do something
}
})
});
Use .map() function to pass each element in the current matched set through a function, which will produce new jQuery object containing the return values.
Here is a code:
$("input[type=checkbox]").on("click", function () {
$( ":checked" ).map(function() { return $(this).closest("tr").text();
}).get().join(); //Use join to split the fetched row using separator "," on server-side
});
Demo: http://jsfiddle.net/tSeau/1/

Dropdown List Value From SQL in PHP

I want to do this function in php. i have two fields, one is text box and an
other one is drop down list. Drop down list contains values from sql. When one of the value is selected from the drop down list i want the text box to be filled according to the option which is selected.
Following is the drop down list code,
<td>Test Group ID</td>
<td><select id="testgroupid" name="testgroupid" style="column-width:35">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH)){
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select></td>
According to the id,I want textbox to be filled, How can i do this ? Pls help friends.
<tr>
<td>Test Group Name</td>
<td><input type="text" name="testgroupname" id="zipsearch" value="<?php echo $testgroupname; ?> "></td>
</tr>
If you want your textbox to be filled immediately after the dropdown selection changes, the simplest way is to use javascript:
<td><select id="testgroupid" name="testgroupid" style="column-width:35"
onchange='document.getElementsByName("testgroupname")[0].value =
document.getElementById("testgroupid").options[e.selectedIndex].value;'>
You need JavaScript for that. Use jQuery (or your favorite library) and bind an event listener to the combobox.
Example with jQuery:
$("#myCombo").change(function(e){
$("myTextField").val( $("#myCombo").val() );
});
I have one suggestion which involves jQuery. I do not know if you are using this library, but I am posting it anyway :)
<script type="text/javascript">
$(function() {
$("#testgroupid").change(function{
$("#zipsearch").text($(this option:selected).val();
});
});
</script>
On change event on the dropbown-box, this function fires, and sets the zipsearch-input accordingly.
I am not sure where $testgroupname comes from but I take it you would like to get that value upon selection in the dropdown. If you don´t have the value available on the client you have to retrieve it from the server somehow.
You can´t use PHP to fill the text box since you do not send your posts when an options is selected in the dropdown. There are many alternatives on how to solve this. I would personally use Ajax to fill the textbox without posting to server.
Good place to start:
http://buffernow.com/2012/08/cascading-dropdown-ajax/
html
<select id="testgroupid" name="testgroupid"
style="column-width:35" onChange=filltext();>
javascript
function filltext()
{
var e = document.getElementById("testgroupid");
var group = e.options[e.selectedIndex].text;
document.getElementById("zipsearch").value= group ;
}
your php code is wrong here
<option value="<?=$res['Id'];?>"><?=`$res['Id']`;?></option>
change to
<option value="<?=$res['Id'];?>"><?=$res['GROUP_NAME'];?></option>
Try like this
<script>
function selecteditem(selectedval)
{
jQuery.post("<?php echo JURI::root().'test.php'?>", { id: selectedval },
function(data) {
jQuery('.zipsearch').val(data);
});
}
</script>
//test.php on the root
<?php
$val=$_POST['id'];
//do what you want with $val
//and say final output is in variable $result than echo it
echo $result;
?>
<!--html code here-->
<select id="testgroupid" name="testgroupid" style="column-width:35" onclick="selecteditem(this.value);">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH))
{
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select>
<input type="text" name="testgroupname" id="zipsearch" class="zipsearch" value="<?php echo $testgroupname; ?> ">
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '</form>';
?>
<script language="JavaScript">
function send_input1(){
document.send1.input4.value = document.send3.populate.value;
}
</script>
<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>

save PHP form data without submit on page refresh

I have two forms in the page one is filter, second is the item list, when I apply the filter to item list form, selected values reset to default. For filter I can save selected values, because I submit this form via POST method, but other remains not submited is possible to save selected that form values after page refresh? Here is some code of second form:
<form name="forma" method="post" onMouseOver="kaina();" onSubmit="return tikrinimas()" action="pagrindinis.php?page=generuoti.php">
<table width="540" border="1" align="center">
<tr>
<td>Client:</td>
<td>MB:</td>
<td>Price:</td>
</tr>
<tr>
<td>
<?php
$query="SELECT name,surname,pers_code FROM Clients";
mysql_query("SET NAMES 'UTF8'");
$result = mysql_query ($query);
echo "<select name=Clients id='clients'>";
echo "<OPTION value=''>- Choose -</OPTION>\n";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
echo "</select>";
?></td>
</tr>
</form>
You need to set the selected attribute of your select element based on what is in $_POST. Something like:
$selected = $_POST['Client'];
while($nt=mysql_fetch_array($result)){
if ($selected == $nt[pers_code]) {
echo "<option value=$nt[pers_code] selected="selected">$nt[name] $nt[surname]</option>";
}
else {
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
}
Also note that you should probably sanitize any values you get from $_POST.
Unfortunately there is no easy way to do this, and it's something that PHP and web developers in general have maligned for years, because repopulating form fields is never easy AND clean.
Values in the form you aren't submitting wont be sent (via GET or POST), so you're left with writing a custom workaround.
While it's a bit Q&D, I would recommend sending an Ajax call on form submit to store the values for your second form in the $_SESSION variable.
I'm sorry to say there's no easy alternative - due to the stateless nature of HTTP requests, this is something that every programmer has to struggle with.
just to break the question down to a more simplified form, let's assume we don't have the hassle of working with dropdowns. The real issue you're having is to take a value from form 1 and have it work even after form 2 has been submitted.
If you use a hidden field on form 2, of the same name as form 1, and populate it based on both form 1 and form 2's POST data, it will be "remembered"
<? // mostly html with a bit of php. ?>
<form id="f1" method="POST">
<input type ="text" name="f1val" value="<?= htmlspecialchars( array_key_exists( 'f1val', $_POST )?$_POST['f1val']:'' ); ?>">
<input type="submit">
</form>
<form id="f2" method="POST">
<input type="hidden" name="f1val" value="<?= htmlspecialchars( array_key_exists( 'f1val', $_POST )?$_POST['f1val']:'' ); ?>">
<input type ="text" name="f2val" value="<?= htmlspecialchars( array_key_exists( 'f2val', $_POST )?$_POST['f2val']:'' ); ?>">
<input type="submit">
</form>
<script type="text/javascript" src="js/jquery1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#forma").submit(function(event) {
var 1stformfield = $form.find( 'input[name="misc"]' ).val();
/* stop form from submitting normally */
//event.preventDefault();
$.post("1stformsubmit.php", $("#forma").serialize());
//after it posts you can have it do whatever
//just post code here
$('#iframe1').attr('src', 'iframepage.php?client=' + 1stformfield);
window.frames["iframe1"].location.reload();
return false;
});
});
</script>
<form name="1stform" method="post" action="/">
<input type="text" name="misc" id="misc" />
<input type="submit" name="submit" id="submit" value="submit 1st form"/>
</form>
<iframe id="iframe1" src="" scrolling="no" ></iframe>
iframe page
<form name="forma" method="post" onmouseover="kaina();" action="/">
<table width="540" border="1" align="center">
<tr>
<td>Client:</td>
<td>MB:</td>
<td>Price:</td>
</tr>
<tr>
<td>
<?php
$selected = $_GET['Client'];
$query="SELECT name,surname,pers_code FROM Clients";
mysql_query("SET NAMES 'UTF8'");
$result = mysql_query ($query);
echo "<select name=Clients id='clients'>";
echo "<OPTION value=''>- Choose -</OPTION>\n";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
echo "</select>"; ?></td>
</tr>
</form>
This will post all inputs inside your form to the file you specify then you can have it do whatever you like, for example show a thank you message..Hope it helps.

Categories