I've been stuck on this for days. I really appreciate your help.
I'm working on a php form that generates dynamically added rows when
the user click the button ADD.
To save the values into the database, users must click the SUBMIT
button.
The problem that i'm facing is that the database doesn't save the
values from the dynamic rows.
AUTOCOMPLETE & DYNAMIC ROWS
<script>
//autocomplete
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#ItemName" ).autocomplete({
source: "user/requisition_search.php",
minLength: 1,
select: function( event, ui )
{
$('#ItmId').val(ui.item.id);
$('#StkId').val(ui.item.stkId);
$('#ItmNameDis').val(ui.item.value);
$('#ItmUOM').val(ui.item.uom);
$('#ItmQty').val(ui.item.qty);
}
});
});
//dynamic rows
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row =
'<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId[]" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty[]" value="'+$("#ReqQty").val()+'"/></td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
});
</script>
HTML
<form name="jqtest" action="submit.php" method="post">
<label for="ItemName">Search : </label>
<input id="ItemName" size="50"/>
<label for="ItmId">Item Id </label>
<input name="ItmId" id="ItmId" readonly="readonly"/>
<label for="StkId">Stock Id </label></td>
<input name="StkId" id="StkId" readonly="readonly"/>
<label for="ItmNameDis">Item Name </label>
<input name="ItmNameDis" id="ItmNameDis" size="50" readonly="readonly"/></td>
<label for="ItmUOM">Unit Of Measurement </label>
<input name="ItmUOM" id="ItmUOM" readonly="readonly"/>
<td><label for="ItmQty">Quantity Available </label>
<input name="ItmQty" id="ItmQty" readonly="readonly"/>
<label for="ReqQty">Quantity </label>
<input name="ReqQty" id="ReqQty" onkeypress="return numbersOnly(event)" onkeyup="ItmQty_Availability()" disabled="disabled"/>
<p>
<input type="reset" name="reset" id="reset" value="RESET"/>
<input type="button" name="add" id="add" value="ADD"/>
</p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
<table id="dataTab" width="90%" style="display:none;" border="1" cellpadding="0" cellspacing="0">
<tr>
<th>Item ID</th>
<th>Stock ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity Available</th>
<th>Quantity Requested</th>
</tr>
</table>
<p> </p>
<p><input style="display:none;" type="submit" name="submit" id="submit" value="SUBMIT"/></p>
</form>
submit.php
<?php
$num = $_POST['rowcount'];
for($i=0;$i<$num;$i++)
{
$strStkId = "";
if(!empty($_POST)){
if(isset($_POST["StkId[]"])){
$strStkId = $_POST["StkId[]"];
}else{
echo "<font color=red>Enter the Stock Id</br></font>";
}
}
$strReqQty = "";
if(!empty($_POST)){
if(isset($_POST["ReqQty[]"])){
$strReqQty = $_POST["ReqQty[]"];
}else{
echo "<font color=red>Enter the Quantity</font>";
}
}
$tsql =
"INSERT INTO REQUISITION
(RequestQuantity, StockId)
VALUES
('$strReqQty','$strStkId')
";
$result = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if (!$result) {
die ('<script>
window.alert("Please enter the requisition details !")
window.location.href = "requisition.php"; </script>');
}
else
echo '<script>alert("Your Requisition is In Process"); </script>';
sqlsrv_close($conn);
}
?>
UPDATED
I've learnt that name="StkId" and name="StkId[]" clashes in the dynamic rows and the inputs.
So i've change into something like this :
var row = '<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId2" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty2" value="'+$("#ReqQty").val()+'"/></td></tr>';
Now the data are inserted into the database but IF the user enters more than one item, only one data is inserted into the database. What did i do wrong? I guess its at the submit.php part but i can't figure out why.
You won't get dynamically generated row values in $_POST on submitting the form because those are not at all form inputs but just displaying as row in a table. But you can achieve your functionality with the help of jQuery AJAX. On clicking the submit button, calls your submit.php using AJAX. The sample solution for how to retrieve values of those dynamically rows is given below. You can adapt this method for your requirement.
Main Page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Dynamic Rows</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row = '<tr class="dynamic" id="'+rowcount+'"><td>'+$("#itemid").val()+'</td><td>'+$("#itemname").val()+'</td><td>'+$("#uom").val()+'</td><td>'+$("#quantity").val()+'</td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
$("#submit").on("click",function(){
alert("submit");
var jsonObj = [];
i=0;
$("#dataTab tr.dynamic").each(function(){
var td = $(this).find('td');
itemId = td.eq(0).text();
itemName = td.eq(1).text();
uom = td.eq(2).text();
quantity = td.eq(3).text();
jsonObj.push({
itemId: itemId,
itemName: itemName,
uom: uom,
quantity: quantity,
});
});
var dataString = JSON.stringify(jsonObj);
$.ajax({
url: "submit.php",
type: "POST",
data: {json:dataString},
success: function(response){
alert(response);
}
});
});
});
</script>
</head>
<body>
<form name="jqtest" action="#">
Item ID : <input type="text" name="itemid" id="itemid"/><br/><br/>
Item name : <input type="text" name="itemname" id="itemname"/><br/><br/>
UOM : <input type="text" name="uom" id="uom"/><br/><br/>
Quantity : <input type="text" name="quantity" id="quantity"/><br/><br/>
<p> <input type="reset" name="reset" id="reset" value="RESET"/> <input type="button" name="add" id="add" value="ADD"/> </p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
</form>
<table id="dataTab" style="display:none;" border="1">
<tr>
<th>Item ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity</th>
</tr>
</table>
<p> <input style="display:none;" type="button" name="submit" id="submit" value="submit"/> </p>
</body>
</html>
submit.php
<?php
$arr = json_decode($_POST['json']);
for($i=0; $i<count($arr); $i++)
{
echo "Row ".$i."\n";
echo "itemId > ".$arr[$i]->itemId.", itemName > ".$arr[$i]->itemName.", uom > ".$arr[$i]->uom.", quantity > ".$arr[$i]->quantity."\n";
}
?>
Related
I have the following problem, I am trying to use JQUERY and AJAX, but when I use the Post method, it does not post to the php file. I get an error undefined array key I know there are many more threads with this question, I've searched them all, watched a lot of tutorials, but nothing helps. The mistake remains. The weirdest thing is when I do a success check to see the value it shows the correct value. My source code is:
SevenTops_Test3.php
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Seven Tops Plovdiv</title>
<link rel="stylesheet" type="text/css" href="Style/mystyle2.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="Script/MyScript2.js"></script>
<script src="jquery-3.6.3.js"></script>
<script src="Raion.js"></script>
<script>
$(document).ready(function () {
$("#Raion").change(function () {
var x = $(this).val();
alert(x),
$.ajax({
url: 'fresh_db_raion3.php',
type: 'POST',
data: { raion : x },
success: function (data) {
alert(x);
// Stuff
},
error: function (data) {
alert("Not Ok");
// Stuff
}
});
});
});
</script>
<script>
$(document).ready(function () {
$("#Query").click(function () {
var x = 5;
alert(x);
$("#lists").load("fresh_db_raion3.php", { raion : x});
});
});
</script>
</head>
<body>
<?php
include 'db_connection_string.php';
include 'fresh_db_raion3.php';
?>
<div id="Top_Button">
<table>
<tr>
<td>
<input type="submit" class="Submit" id="Query" name="query" value="Заявка">
</td>
<td>
<input type="submit" class="Submit" id="Read" value="Преглед" />
</td>
<td>
<input type="submit" class="Submit" id="Delete" value="Изтрий" />
</td>
<td>
<button type="submit" class="Submit" id="Menu">
<img src="Picture/Menu.png" id="Menu_Img" />
</button>
</td>
</tr>
</table>
</div>
<hr />
<div>
<select id="Raion" name="raion" >;
<option selected disabled> Избор</option>
<?php
all_raion();
?>
</select>
</div>
<div id="lists" style="overflow:scroll;">
<?php
db_klient();
?>
</div>
<div id="Down_Control">
<table>
<tr>
<td>
<input type="number" id="number" />
</td>
<td>
<input class="label_down" id="label_down1" value="%" readonly>
</td>
<td>
<input type="checkbox" class="Submit" id="check" />
</td>
<td>
<input type="button" value="Запиши" class="Submit" id="Down_Btn_Insert" />
</td>
<td>
<textarea id="label_down2" readonly>кашон/стек</textarea>
</td>
<td>
<input type="checkbox" class="Submit" id="check1" />
</td>
</tr>
</table>
</div>
</body>
</html>
fresh_db_raion3.php
<?php
include "db_connection_string.php";
$getraion = $_POST['raion'];
echo $getraion;
function all_raion(){
$result_raion = $GLOBALS['db']->query('SELECT * FROM Raion');
$rowas_raion = $result_raion->fetchAll(PDO::FETCH_ASSOC);
foreach ($rowas_raion as $GLOBALS_k => $v)
{
echo '<option value=' . $GLOBALS_k . '>' . $v['Raion_Name'] . '</option>';
}
}
function db_klient(){
print_r( $GLOBALS['getraion']);
echo '<br>';
$result_klient = $GLOBALS['db']->query("SELECT* FROM Klient WHERE Raion_ID=". $GLOBALS['getraion']);
$row_klient = $result_klient->fetchAll(PDO::FETCH_ASSOC);
foreach ($row_klient as $kk => $vv)
{
echo '<input type=radio value=' . $vv['Klient_Name'] . ' name = klient_name>
<label>'. $vv['Klient_Name'] . '</label><br>';
}
}
I know the code must be very lame, but I'm very new..
And the database schema is this:
Raion CREATE TABLE "Raion"("Raion_ID" INTEGER PRIMARY KEY, "Raion_Name" TEXT NOT NULL)
Kategorii CREATE TABLE "Kategorii" ( "Kategorii_ID" INTEGER PRIMARY KEY, "Kategorii_Name" TEXT NOT NULL)
Stoki CREATE TABLE "Stoki" ( "Stoki_ID" INTEGER PRIMARY KEY, "Kategorii_ID" INTEGER NOT NULL, "Stoki_Name" TEXT NOT NULL)
Klient CREATE TABLE "Klient" ("Klient_ID" INTEGER PRIMARY KEY, "Raion_ID" INTEGER NOT NULL, "Klient_Name" TEXT NOT NULL)
youtube tutorials, answers in various topics in here in the forum
I am looking to calculate a column within a table that is being created. I need the sum field to add up the values created from the form, which is created new rows for the table upon submit. Any way I can get the to add up the column sum? Each time a function updatetable() is run is creates another table row, and these are the rows I need calculated...currently the column holds a "184" as a holding place for where the calculation would take place.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>The real test</title>
<link rel="stylesheet" href="html_testing.css">
<script type="text/javascript"> <!--
var tabBody, row, cell;
function updateTable(){
tabBody=document.getElementById("joe$");
row=document.createElement("tr");
row.setAttribute("id","js");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[2].value;
row.appendChild(cell);
if(tabBody.childNodes.length==17)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
function updateTable1(){
tabBody=document.getElementById("joe");
row=document.createElement("tr");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[3].value;
row.appendChild(cell);
if(tabBody.childNodes.length==17)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
function myFunctionJoe(){
updateTable();
updateTable1();
}
function moneymoney(){
('#joe$ tr:first td').each(function(){
var $td = $(this);
var colTotal = 0;
$('#joe$ tr:not(:first,.totalColumn)').each(function(){
colTotal += parseInt($(this).children().eq($td.index()).html(),10);
});
$('#joe$ tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});
}
</script>
<body>
<h2>Legion of Roar:</h2>
<form name="leds" id="ledSend" action="" onsubmit="return false;">
Lamp Control: <input type="radio" name="led" value="0" checked />Off
<input type="radio" name="led" value="1" />On<br>
Winning Bid: <input type="text" name="timer" placeholder="Bid..." /><br>
Player Drafted: <input id="name" type="text" name="user" placeholder="Player Name..." /><br>
Player Position: <input id="name" type="text" name="user" placeholder="Position..." /><br>
<br>
<input type="submit" value="Joe" onclick="myFunctionJoe();"/>
<h1>Testing some skills</h1>
<fieldset>
<table border ='1' class="inlineTable">
<thead><tr><th>Joe</th></tr></thead>
<thead><tr><th>200</th></tr></thead>
<tr class="totalColumn">
<td class="totalCol">Spent:</td>
</tr>
<tbody id="joe"><tbody>
</table>
<table border ='1' class="inlineTable">
<thead><tr><th>$</th></tr></thead>
<thead><tr><th>184</th></tr></thead>
<tr class="totalColumn">
<td class="totalCol">Spent:</td>
</tr>
<tbody id="joe$"><tbody>
</table>
</body>
</html>
I'm having a problem. I'm creating a dynamic table with jquery (the user insert a value and then it creates the table). Now in the Table I have a Select tab with pre-defined values that are coming from a table in my database (mysql).
this is my code:
$(document).ready(function() {
$("#submit").click(function(e) {
$("#Table").empty();
e.preventDefault();
if($("#NumOfLevels").val() >0)
{
var size = $("#NumOfLevels").val();
var str='';
str+='<table align="center" width="694" border="0" cellspacing="3" cellpadding="0">';
str+='<tr><th style="width:auto" scope="col">level </th><th width="107">score</th><th width="58">game file</th><th width="80">catalog</th><th width="93">start date</th><th width="85">end date/th></tr>';
for(var i = 0; i< size ; i++)
{
str+='<tr><td id="stage'+i+'" style="width:auto">level '+(i+1)+'</td><td><span id="sprytextfield4"><input type="text" name="Score" id="Score"/>';
str+='<span class="textfieldRequiredMsg">A value is required.</span></span></td>';
str+='<td><input type="file" name="gameFile" id="gameFile" /></td>';
str+='<td><select multiple="multiple" name="CatlogLink" id="CatlogLink">';
**Here Is Where I Need To Enter My PHP Function**
str+='</select></td>';
str+='<td><input type="text" class="date" id="datepicker" ></td>';
str+='<td><input type="text" class="date" id="datepicker2" "></td>';
//str.find('input').datepicker();
}
//str+='</tr></table>';
$("#Table").append(str);
var btn = '';
btn+='<tr><td width="192" colspan="2" align="center"><input type="submit" name="Submit" id="submit" value="submit"/></td>';
btn+='<td width="309" colspan="4" align="center"><input type="reset" name="reset" id="Clear" value="clear" /></td></tr></tr></table>';
$("#Table tr:last").after(btn);
}
$(".date").click(function() {
$( ".date" ).datepicker();
$( ".date" ).datepicker();
});
});
});
and my question is how to get the php code that generates the option list to integarte with my javascript code.
My Php Function only retrieve some values (Names) I don't send to the function any data.
Regards,
Yotam.
I create an addline array button that creates multiple array fields my problems is that I can't save the data that inserted to the fields.
JavaScript
var MaxInputs = 3; //maximum input boxes allowed
var InputsWrapper = $("");
var addlines = 1;
var FieldCount = 1; //to keep track of text box added
function AddORDeleteLines(obj,type){
type=type+'';
var objtype=obj.id+'';
if(type==="add"){
if(objtype==='AddMoreLines'){
if(addlines<=MaxInputs){
FieldCount++;
InputsWrapper = $("#ADD_LINE-txtEmployee-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="text" name="txtEmployee" size="30"/>'+
'</div>');
InputsWrapper = $("#ADD_LINE-txtDate-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="date" name="txtDate"/>'+
'</div>');
InputsWrapper = $("#ADD_LINE-txtTimeFrom-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="time" name="txtTimeFrom" />'+
'</div>');
InputsWrapper = $("#ADD_LINE-txtTimeTo-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="time" name="txtTimeTo" />'+
'<input type="button" onClick="AddORDeleteLines(this,'+"'delete'"+')" id="removeButton_'+FieldCount+'" value="x" class="removeLines"/>'+
'</div>');
addlines++;
}
}
}
else if(type==="delete"){
var parentobj = $("#"+obj.id).parent('div');
//$(parentobj).parent('div').remove();
var objclass = $("#"+obj.id).parent('div').attr("class")+'';
objtype = $("#"+obj.id).attr("class")+'';
if(objtype==='removeLines'){
addlines--;
}
$("div").remove('.'+objclass);
return false;
}}
View
<table>
<tr>
<td>
<div id="ADD_LINE-txtEmployee-div">
<input type="text" id="txtEmployee" name="txtEmployee" size="30"/>
</div>
</td>
<td>
<div id="ADD_LINE-txtDate-div">
<div>
<input type="date" id="txtDate" name="txtDate" />
</div>
</div>
</td>
<td>
<div id="ADD_LINE-txtTimeFrom-div">
<div>
<input type="time" id="txtTimeFrom" name="txtTimeFrom" />
</div>
</div>
</td>
<td>
<div id="ADD_LINE-txtTimeTo-div">
<div>
<input type="time" id="txtTimeTo" name="txtTimeTo" />
<input type="button" id="AddMoreLines" onclick="AddORDeleteLines(this,'add')" value="ADD LINE" />
</div>
</div>
</td>
</tr>
Controller
public function SaveOvertime(){
$this->load->library('form_validation');
$this->form_validation->set_rules('txtEmployee[]', 'Employee', 'required');
$this->form_validation->set_rules('txtTimeFrom[]', 'Time From', 'required');
$this->form_validation->set_rules('txtTimeTo[]', 'Time to', 'required');
$this->form_validation->set_rules('txtDate[]', 'Date', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('error_overtime');
}
else
{
$this->load->model('dtr_model');
$this->dtr_model->saveovertime();
$this->load->view('success_overtime');
}
MODEL
function saveovertime(){
$value = array(
'EMPLOYEE'=>$this->input->post('txtEmployee[]'),
'TIME_FROM'=>$this->input->post('txtTimeFrom[]'),
'TIME_TO'=>$this->input->post('txtTimeTo[]'),
'DATE'=>$this->input->post('txtDate[]'));
$query = $this->db->insert('dtr_timerecord_overtime_line',$value);}
I think you need to store these multiple values of each field by using json_encode() or serialize() functions of php. Replace your saveovertime() function with below function:
function saveovertime(){
$value = array(
'EMPLOYEE'=>json_encode($this->input->post('txtEmployee')),
'TIME_FROM'=>json_encode($this->input->post('txtTimeFrom')),
'TIME_TO'=>json_encode($this->input->post('txtTimeTo')),
'DATE'=>json_encode($this->input->post('txtDate')));
$query = $this->db->insert('dtr_timerecord_overtime_line',$value);}
I have some code I am using that works well cloning the contents of a div as many times as needed.
The original code would rename the name/id of each form field. so the first clone the name would be "name1" second clone "name2" etc...
The problem is when I put the form fields within a div or a table for design purposes.
The code doesn't rename the form fields anymore as it seems to refer to the top elment which is the table or div (depending which I used)
Here is a cut down version of the code that contains everything needed for this example (can be copied into an editor and will work as is. You will see the field id's are not being renamed):
www.jsbin.com/oyavez/1/edit
<script type="text/javascript">
var formCounter = 0;
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
formCounter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + formCounter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
<title>Add Orders IO TOC</title>
</head>
<body>
<!-- Template -->
<div id="readroot" style="display: none">
<table>
<tr><td colspan="2"><h3>Order <script>document.write(formCounter);</script></h2></td></tr>
<tr><td>Order ID: </td><td><input type="text" id="OrderID name="OrderID[]" ></input></td>
<td>Order Name: </td><td><input type="text" id="OrderName" name="OrderName[]" ></input></td>
</table>
<br /><br /><input type="button" value="Remove Above Order" style="width:200px;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<!-- ROW -->
</div>
<!-- END Template -->
<!-- Start of form -->
<form method="get" action="form.php">
<table>
<tr><td align="center" colspan="2"><h2>Contract</h2></td></tr>
<!-- Static part of the form not to be cloned -->
<tr><td>Contract: </td><td><input type="text" id="Contract" name="Contract" ></input></td>
<td>Signed Date: </td><td><input type="text" id="datepicker0" name="SignedDate" ></input></td>
<tr><td align="center" colspan="2"><h2>Orders</h2></td></tr>
</table>
<!-- ROW -->
<!-- Cloned parts of the form appear here -->
<span id="writeroot"></span>
<table>
<tr><td align="center" > <input type="button" style="width:200px;" value="Add another order below" onclick="moreFields()" /></td>
<td align="center" ><input type="submit" value="Submit IO and all Orders" style="width:200px;" ></td></tr>
</table>
</form>
Anyone know how to get to the child of the table it would seem?
Thanks!