Looping through serialized data to insert updates to MySQL DB - php

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.

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

Can't get dynamic table elements value using jquery

I want to get the values of a dynamic created table but I couldn't figure out what is wrong.
the table created in a php file or it creates in server side by calling it in jquery.
for making it clear : in my html page I run a jquery method to load this table.
then I need this table values to be able to edit them. but what I get instead of the element value is undefined. (when I alert the value)
this is the jquery code :
//<!-- ajax Post Request -->
$(function() {
$('#edit_test_show').hide();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
read_OPS: true,
op_id: vop_id
},
function(response) { // Required Callback Function
if (response) {
$("#result_table").html(response);
}
});
//====================
$('#enable_edit').on('click', function() {
$('#edit_test_show').show();
$('#enable_edit').hide();
$('#save_edit').show();
});
$('#save_edit').on('click', function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('#op_title').val();
var vop_descrip = $('#result_table').find('#op_descrip').val();
alert(vop_title);
});
});
html part which the table loads in :
<form method='post' class="form-inline">
<div class="form-group">
<div id="result_table">
<!-- dynamic op load -->
</div>
</div>
</form>
<button type='button' id="enable_edit" class='btn btn-default'>edit</button>
<button type='button' id="save_edit" class='btn btn-default'>save</button>
and this is the php code which generate the table :
if($row=mysqli_fetch_assoc($read_op)) {
echo "
<table class='styled-table' cellspacing='0' width='360' border='1' >
<tr>
<td>
<label for='mail_num' style='margin-right:10px;color:#595959;float: right;'>شماره فرآیند : </label>
</td>
<td>
<input name='op_id' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['id']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_title' style='margin-right:10px;color:#595959;float: right;'>عنوان فرآیند : </label>
</td>
<td>
<input name='op_title' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['op_title']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_descrip' style='margin-right:10px;color:#595959;float: right;'>شرح فرآیند : </label>
</td>
<td>
<textarea name='op_descrip' class='textarea_2' rows='0' cols='0' >".$row['op_descrip']."</textarea>
</td>
</tr>
</table>
<div class='cleaner h20'></div>";
}
You are using ID Selector (“#id”) but not defined ID in HTMl thus you are not able to find element
Define the IDs as
<input id='op_id' value='".$row['id']."'/>
OR, Use Attribute Equals Selector [name=”value”]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();

How to Insert to database from loop Using PHP?

The problem occurs when I insert without data. So I want your help in solving this problem.
This is my file:
students.php
<form id="student_form" method="POST" action="">
<?php
if(mysql_num_rows($q)>0){
?>
<table border="0" dir="ltr" align="center"cellpadding='0' cellspacing='0' >
<tr> <th>Student ID</th><th>Name</th><th>AVG</th><th>Joining Year</th><th>Message</th><th>Sending Message</th> </tr>
<?php while($row = mysql_fetch_array($q)){ ?>
<tr>
<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
<td> <?php echo $row['studant_Name']; ?></td>
<td> <?php echo $row['Average']; ?></td>
<td> <?php echo $row['year']; ?></td>
<td> <input id="message1[]" name="message1[]" type="text" size="25px" /></td>
<td><input name="submit[]" id="submit[]" type="submit" value="Send" /> </td>
</tr>
<?php }}
and this is my insert file:
insert_message.php
if (isset($_POST['message1']) && $_POST['message1']!='') {
$addss = mysql_real_escape_string($_POST['message1']);
}
if (isset($_POST['stud_id']) && $_POST['stud_id']!='') {
$std_id = mysql_real_escape_string($_POST['stud_id']);
}
//#######################################################################
$query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$std_id', '22011111', '$addss'); ";
mysql_query($query1);
I connect between two file by jquery and ajax.
<script>
$("#student_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_message.php",
data: $(this).serialize(),
success: function(data) {
$("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
Remove the form from the page
<tr>
<td id="stud_id"> <?php echo $row['studant_ID']; ?>
<input type="hidden" name="stud_id" value="<?php echo $row['studant_ID']; ?>"/>
</td>
<td> <?php echo $row['studant_Name']; ?></td>
<td> <?php echo $row['Average']; ?></td>
<td> <?php echo $row['year']; ?></td>
<td> <input id="message1" name="message1" type="text" size="25px" /></td>
<td><button class="submit" type="submit" />Send </button> </td>
</tr>
second:
your js should look like this:
$(".submit").on("click", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_message.php",
data: {stud_id:$(this).closest('tr').find('input[name="stud_id"]').val(),message1:$(this).closest('tr').find('input[name="message1"]').val()},
success: function(data) {
$("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
In insert_message.php
you need to echo a message to see if you where succesful in updating the database
echo json_encode(array('message'=>'Data updated/Error'));
First of all - all data passed to server in a $_POST array is taken from input fields with name attribute (unless you have some custom js handlers).
So
<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
does nothing.
If you want to store studant_ID somehow - use hidden field for example:
<td>
<input type="hidden" name="stud_id[]" value="<?php echo $row['studant_ID']; ?>" />
</td>
Next - what do you want from this buttons:
<input name="submit[]" id="submit[]" type="submit" value="Send" />
As they are all belong to one form they will do the same - send all fields to server. If you want every submit button send to server only a pair student_id, message you have to create a form for each pair (or do some js-handlers). Otherwise, on your server you'll have:
$_POST['stud_id'] array of all students ids from form
$_POST['message1'] array of all messages from form
If you want to process them all - do a foreach:
foreach ($_POST['stud_id'] as $key => $id) {
// find the message
$msg = $_POST['message1'][$key];
$query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$id', '22011111', '$msg'); ";
mysql_query($query1);
}
And of course you should remove mysql_ functions and use newer apis - PDO or mysqli

Displaying Data from mysql table

I have created this form using the while loop so that i dont have to make 28 text field ... but when i submit the data into my mysql database it works well but how to display the data back to my form for edit and update .. when i type a value to a text field (EX - submitted data from mysql in emp_name field) then it repeated 4 times in the text field .... i know it is happening because of loop but is there any way that i can display multiple data in each text field for updating after submitting data by the user as normal ....
my form.php
<form action="userdata.php" name="frmAdd" method="post">
<table width="80%" border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<td width="5"> <div align="center">NO</div></td>
<td width="91"> <div align="center">Employer's NAME</div></td>
<td width="160"> <div align="center">COUNTRY</div></td>
<td width="198"> <div align="center">POSITION</div></td>
<td width="70"> <div align="center">FROM</div></td>
<td width="70"> <div align="center">TO</div></td>
<td width="70"> <div align="center">SALARY</div></td>
<td width="70"> <div align="center">REASONS FOR LEAVING</div></td>
</tr>
<?php for($i=1;$i<=4;$i++) { ?>
<tr>
<th width="5"> <div align="center"><? echo $i . "."; ?></div></th>
<td><input type="text" name="emp_name<?=$i;?>" size="25" value="submitted data from mysql"></td>
<td><input type="text" name="emp_country<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_pos<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_frm<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_to<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_sal<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_lev<?=$i;?>" size="25"></td>
</tr>
<?php } ?>
</table>
</br>
<input type="submit" name="doHis" value="Save Employment History">
<input type="hidden" name="hdlfrm" value="<?=$i;?>">
</form>
and my userdata.php
if($_POST['doHis'] == 'Save Employment History')
{
try{
$conn = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
for($i=1;$i<=$_POST["hdlfrm"];$i++){
if($_POST["emp_name$i"] != ""){
$sql = "INSERT INTO emp_table (emp_name, emp_country, emp_pos, emp_frm, emp_to, emp_sal, emp_lev)
VALUES (:emp_name, :emp_country, :emp_pos, :emp_frm, :emp_to, :emp_sal, :emp_lev)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':emp_name', $_POST["emp_name$i"]);
$stmt->bindParam(':emp_country', $_POST["emp_country$i"]);
$stmt->bindParam(':emp_pos', $_POST["emp_pos$i"]);
$stmt->bindParam(':emp_frm', $_POST["emp_frm$i"]);
$stmt->bindParam(':emp_to', $_POST["emp_to$i"]);
$stmt->bindParam(':emp_sal', $_POST["emp_sal$i"]);
$stmt->bindParam(':emp_lev', $_POST["emp_lev$i"]);
$stmt->execute();
echo "Save Done. Click <a href='phpMySQLListRecord.php'>here</a> to view.";
}
}
}
and here is the snapshot
The problem you have is your data model - you are saving employment history, but for who? It needs to have an employee_id somewhere to say who this data belongs to, and join it to a table that saves the employee_table data. Next you need to have a unique ID on the emp_table to identify each row, which you can use instead of your $i index.
TABLE
history_id INT autoincrement | employee_id INT | emp_name VARCHAR | your other fields....
SELECT
SELECT history_id, emp_name, ... FROM emp_history where employee_id = ?
You can then loop over the results and use the history_id to identify the row that the data belongs to to update it. Submitting multiple fields with the same name will be an array you can iterate over, so you don't need to use a unique field name for each.
As a side note, you probably want to use isset($_POST["key"]) instead of $_POST["key"] != "" to check if a field was submitted.

Iterating through SQL Data and then Posting Query Results into appropriate input fields

What I'm trying to do here is I have 5 input fields, each has its own total weight for Lane-1,Lane-2,Poly-1,Poly-2,Poly-3 that will be displayed by what's in the database... I could do this with 5 different JS functions and 5 separate php files with SQL statements pertaining specifically to that lane type, but I'd rather do it all in one structure or one file and one JS function, if at all possible? Any ideas how I might go about this? I have it working for just the "else" part of the SQL statement, but I need to get the other data pertaining to the other lane types (lead-2, poly-1, etc...) Thanks in advance!
I can't even say I am doing any of this right, so feel free to chastise me.
HTML
<body onload="getLaneWeight();">
<form id="Warehouse_Worksheet" name="Warehouse_Worksheet">
<table align="center">
<tbody>
<tr>
<th>
Lane Types
</th>
<th>
Total Weight
</th>
</tr>
<tr>
<td>
Lead 1
</td>
<td>
<input type="text" name="Lead-1" readonly="readonly" />
</td>
</tr>
<tr>
<td>
Lead 2
</td>
<td>
<input type="text" name="Lead-2" readonly="readonly" />
</td>
</tr>
<tr>
<td>
Poly 1
</td>
<td>
<input type="text" name="Poly-1" readonly="readonly" />
</td>
</tr>
<tr>
<td>
Poly 2
</td>
<td>
<input type="text" name="Poly-2" readonly="readonly" />
</td>
</tr>
<tr>
<td>
Poly 3
</td>
<td>
<input type="text" name="Poly-3" readonly="readonly" />
</td>
</tr>
</tbody>
</table>
</form>
</body>
JS FILE
//Populate Lane Type Weight Table
function getLaneWeight() {
$.ajax({
type: 'GET',
url: './php/getLaneWeight.php',
data: 'lane_name=Lead-1',
success: function (mydata) {
document.forms['Warehouse_Worksheet'].elements['Lead-1'].value = mydata;
},
error: function () {
},
complete: function () {
getLead2();//Call next Lane Type
}
});
};
//Set Next Lane Weight
function getLead2() {
$.ajax({
type: 'GET',
url: './php/getLaneWeight.php',
data: 'lane_name=Lead-2',
success: function (mydata) {
document.forms['Warehouse_Worksheet'].elements['Lead-2'].value = mydata;
//alert(document.forms['Warehouse_Worksheet'].elements['Lead-1'].value);
},
error: function () {
},
complete: function () {
//getPoly1();//Call next Lane Type
}
});
};
PHP/SQL
if(isset ($_GET['Poly-2'])){
$sql="SELECT SUM(weight)
FROM bundle_lanes
WHERE lane_name = 'Poly-3'";
}else if(isset ($_GET['Poly-1'])){
$sql="SELECT SUM(weight)
FROM bundle_lanes
WHERE lane_name = 'Poly-2'";
}else if(isset ($_GET['Lead-2'])){
$sql="SELECT SUM(weight)
FROM bundle_lanes
WHERE lane_name = 'Poly-1'";
}else if(isset ($_GET['Lead-1'])){
$sql="SELECT SUM(weight)
FROM bundle_lanes
WHERE lane_name = 'Lead-2'";
}else{
$sql="SELECT SUM(weight)
FROM bundle_lanes
WHERE lane_name = 'Lead-1'";
}
$result = mysql_query($sql) or die ('Error'.mysql_error());
while ($data = mysql_fetch_row($result)) {
$weight = $data[0];
echo $weight;
}
You than create a function like below
If your php code will definitely get the data you want than you can instantly insert it into the function below. If you want to store all 5 of them than use a for loop and array storing each of the names in php such as
$myarray=('string1','string2');
for($i=0;i<$myarray.length;i++){
sqlQuery($myarray[i]);
}
function sqlQuery($lane_name){
$sql
$sql="SELECT SUM(weight)
FROM bundle_lanes
WHERE lane_name = '".$lane_name."'";
$result=.......
//check if data was stored.
echo(<!-- new html code-->);
}
This will store all 5 of the fields. If you only want 1 of them its better to use a switch case. If your php is in the same file than simply use php to generate the html using echo. You can insert variables that are set like this- echo("some text".$myvar."some more text");
If its a different file you'll need ajax in javascript to recieve the data and use a switch or if else case. For example
if(response=='my response'){
document.getElementById('my textbox').innerHTML(....);
}
my javascript may not be accurate but i hope you get the idea

Categories