I want to send variable rows to post2.php with other HTML form variable using POST or GET methods.
The below code gives an error:
Notice: Undefined index: row1 in C:\xampp\htdocs\PhpProject1\OtherUsableItems\post2.php on line 8
post1.php
<html>
<head>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</script>
<script>
function count(tableId){
var rows = document.getElementById(tableId).getElementsByTagName("TR").length;
// window.location.href = "http://localhost/PhpProject1/OtherUsableItem /post2.php?rows=" + rows ;
// alert('Your table has ' + rows + ' rows.');
$.post("post2.php", { 'row' : rows}, function(rows){alert('rows'+rows);});
}
</script>
</head>
<body>
<form action="post2.php" method="post">
<TABLE id="dataTable" border="1">
<TR>
<TD> 1 </TD>
<TD> <INPUT name="n1[]"type="text" /> </TD>
<TD> <INPUT name="n2[]"type="text" /> </TD>
<TD><SELECT name="country[]" type="select-one">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT></TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable');"/>
<button id="bt" onclick="count('dataTable');">Submit</button>
</form>
</body>
</html>
post2.php
<?php
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
$country = $_POST['country'];
echo $n1[0];
echo $n2[0];
echo $country[0];
$count = $_POST['row1'];
echo $count;
?>
Try changing to 'row' instead of 'row1'
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
$country = $_POST['country'];
echo $n1[0];
echo $n2[0];
echo $country[0];
$count = $_POST['row'];
echo $count;
In the future, use print_r to see the value of $_POST.
In addition to the above instructions, I would remove the 2nd <script> tag from post1.php and place the following code into the body at the start of the form:
<form action="post2.php" method="post" >
<input id="rowNumber" type="hidden" name="row" value="1"/>
Also, add the following lines to function addRow:
var rowNumber = document.getElementById('rowNumber');
rowNumber.value = parseInt( rowNumber.value ) + 1;
The problem is that you are not sending the correct Post value.
check if this line :
var rows =
document.getElementById(tableId).getElementsByTagName("TR").length;
it returns values something like: {name:'value',name2:'value2'}
after that you will be able to access via php using $_POST['name']...
and this line :
$.post("post2.php", { 'row' : rows}, function(rows){alert('rows'+rows);});
replaced with:
$.post("post2.php", rows, function(rows){alert('rows'+rows);});
else you will be accessing with $_POST['row']
Related
I would like to be able to send multiple dropdown values with the same name to insert them in the database
can somebody help me??
<?php
session_start();
require_once('Connections/koneksi.php');
if($_REQUEST['submit'] == "Submit")
{
$name = $_POST["user"];
$masukdatabase = "INSERT INTO `com`(`user`) Values('$ame')";
}
?>
<html>
<head>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cant delete all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form name="form1" method="post" action="adduser.php">
<table id="dataTable" width="auto" style="margin:-4px 0 0 0;" cellspacing="0px">
<tr>
<td style="width:20px;"><INPUT type="checkbox" name="chk" /></td>
<td><select name="user" id="user">
<option value="tono">tono</option>
<option value="tini">tini</option>
</select></td>
</tr>
</table>
<INPUT type="button" value="Add row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete row" onclick="deleteRow('dataTable')" />
</form>
</body>
</html>
What you need to do to send more than 1 select with the same name is make it an array by adding [] and the end of its name name="user" becomes name="user[]". Then when you receive the variable via POST it will be an array
Using your example:
adduser.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
foreach($_POST['user'] as $name)
{
$masukdatabase = "INSERT INTO `com`(`user`) Values('${name}')";
}
}
?>
index.html
<html>
<head>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cant delete all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form name="form1" method="post" action="adduser.php">
<table id="dataTable" width="auto" style="margin:-4px 0 0 0;" cellspacing="0px">
<tr>
<td style="width:20px;"><INPUT type="checkbox" name="chk" /></td>
<td><select name="user[]" id="user">
<option value="tono">tono</option>
<option value="tini">tini</option>
</select></td>
</tr>
</table>
<INPUT type="button" value="Add row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete row" onclick="deleteRow('dataTable')" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I have a form which is cloned when needed, inside this form I have a div, this div is replaced by a div pulled from another page which has new select options based on a select option from a above field.
Each 'cloned' forms fields are given a new name with a function, but this function seems to have trouble seeing the field that is pulled in as part of the form and isn't generating a new name for it.
Could Someone kind enough show me the way please?
function;
$(document).ready(function() {
var newNum = 2;
cloneMe = function(el) {
var newElem = el.clone().attr('id', 'container' + newNum);
newElem.html(newElem.html().replace(/form\[1\]/g, 'form['+newNum+']'));
newElem.html(newElem.html().replace(/id="(.*?)"/g, 'id="1'+newNum+'"'));
$('#cloneb').before(newElem);
$('#delete_name'+ newNum).html('<p id="rem_field"><span>Delete Line</span></p>');
newNum++;
};
$('p#rem_field').live('click', function() {
$(this).parents('div').remove();
return false;
});
});
form;
<form action='' method='post' enctype='multipart/form-data' name='form' id='form'>
<div id="container1">
<div class="instance" id="instance">
<label>Style:</label>
<select name='form[1][style]' id='style' class='style' onchange="showDim(this)">
<option value='0' class='red'>Select a style...</option>
<?php
include ('connect.php');
$getsty = $db->prepare("SELECT Style_ID, Style_Type FROM style ORDER BY Style_Type ASC LIMIT 1, 18446744073709551615;");
$getsty->execute();
while($row = $getsty->fetch(PDO::FETCH_ASSOC)) {
$Style_ID = $row['Style_ID'];
$Style_Type = $row['Style_Type'];
echo " <option value='$Style_ID'>$Style_Type</option>";
}
?>
</select>
<br />
<div class='dimdiv'>
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class='red'>Select the dimensions...</option>
</select>
</div>
<br />
<label>Colour:</label>
<select name='form[1][Colour]' id='Colour'>
<option value='0' class='red'>Select a colour...</option>
<option value='Colour1'>Colour #1</option>
<option value='Colour2'>Colour #2</option>
<option value='Colour3'>Colour #3</option>
<option value='Colour4'>Colour #4</option>
</select>
<br />
<label>Quantity:</label>
<input type='text' name='form[1][Quantity]' id='Quantity'>
<br />
</div>
<div id="delete_name" style="margin:15px 0px 0px 0px; width:120px; height:30px;"></div>
</div>
<input type="button" id="cloneb" value="Clone" onclick="cloneMe($('#container1'));" />
<input type='submit' name='submit' value='Submit' class='buttons'>
</form>
Field pulled from get_dim.php;
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class="red">Select the dimensions...</option>
<?php
$id = intval($_GET['id']);
include ('connect.php');
$getcus = $db->prepare("SELECT Dim_ID, Dim FROM dimentions WHERE Style_ID=? ORDER BY Dim ASC ");
$getcus->execute(array($id));
while($row = $getcus->fetch(PDO::FETCH_ASSOC)) {
$Dim_ID = $row['Dim_ID'];
$Dim = $row['Dim'];
echo " <option value='$Dim_ID'>$Dim</option>";
}
?>
</select>
Function to replace the dimdiv with get_dim.php;
function showDim(elem)
{
var elems = document.getElementsByClassName('style'),
groupIndex = -1,
targetDimDiv,
i;
for( i = 0; i < elems.length; ++i ) {
if( elems[i] == elem ) {
groupIndex = i;
break;
}
}
if( groupIndex == -1 )
{
return;
}
targetDimDiv = document.getElementsByClassName('dimdiv')[groupIndex];
if (elem.value == "")
{
targetDimDiv.innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function( ) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
targetDimDiv.innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","get_dim.php?id="+elem.value,true);
xmlhttp.send();
}
Your problem is, that form[1][Dim] is hard coded into get_dim.php. When you clone a form, you change the name of every element, but this AJAX request would still return a form element with name form[1][Dim] there too.
You can fix this, by reading out the current form id and passing it to get_dim.php and making the name generation there dynamic.
The parts you have to change (roughly):
replace function:
form_id = groupIndex + 1; // if I get groupIndex right
xmlhttp.open("GET","get_dim.php?id="+elem.value+"&form_id="+form_id,true);
get_dim.php:
<select name='form[<?php echo intval($_GET['form_id']); ?>][Dim]' id='Dim'>
For some reasons my javascript form validation does not go through every row in the table.
I created the table with the codes below:
The $usr variable is just a result of another process:
<form name="myForm" action="addAccessories.php" method="post" onsubmit="return validateForm(this);">
<table border="1" id="IT">
<tr>
<th>Barcode<em>*</em></th>
<th>Current stock</th>
</tr>
<?php
for($id=1; $id<=$usr; $id++){
?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $id; ?>" />
<input type="text" name="bar_code<?php echo $id; ?>" id="bar_code<?php echo $id; ?>" value="" /></td>
<td><input type="text" name="num_stock<?php echo $id; ?>" value="0" id="num_stock<?php echo $id; ?>"/></td>
<?php
}
?>
<tr>
<td> </td>
<td> <button data-theme="b" input type="submit" name="Submit" value="Submit">Add accessories</button></td>
</tr>
</table>
</form>
The number of rows from this table is: rows = $usr + 1
My validation form codes:
<script type="text/javascript">
function validateForm(){
var errors = [];
for(i = 1; i < document.getElementById("IT").rows.length; i++){
var barcode = document.getElementById('bar_code'+i).value;
var des = document.getElementById('description'+i).value;
var num_stock = document.getElementById('num_stock'+i).value;
if(barcode == null || barcode == ""){
errors[errors.length] = "You must enter barcode.";
}
if(isNaN(num_stock)){
errors[errors.length] = "Current stock must be an integer";
}
if(num_stock < 0){
errors[errors.length] = "Current stock must be a positive number";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
This process only validates the 1st row in the table then stop. Can anyone show me what went wrong and how to fix it?
Thank you very much for your help
Your code is making life way more complex than it needs to be. A simpler approach is to just deal with the form controls, e.g. since you are already passing a reference to the form from the submit listener:
function validateForm(form) {
var errors = [];
var c, cs = form.elements;
var reB = /^bar_code/;
var reN = /^num_stock/;
var reD = /^[0-9]+$/;
for (var i=0, iLen=cs.length; i<iLen; i++) {
c = cs[i];
if (reB.test(c.name) && c.value == '') {
errors.push('You must enter barcode.'];
} else if (reN.test(c.name) && !reD.test(c.value)) {
errors.push('Stock number must be a positive integer.'];
}
}
// deal with errors...
}
Note that in the test:
> barcode == null || barcode == ""
barcode is a string, so the first test will never return true and the second is sufficient if you want to see if it's empty.
I used below script to add dynamic rows in a form.
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk[]"/></TD>
<TD><INPUT type="text" name="txt[]"/></TD>
<TD>
<SELECT name="country[]">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
<TD><INPUT type="text" name="passport[]"/></TD>
</TR>
</TABLE>
with the use of the following php:
$chkbox = $_POST['chk'];
$txtbox = $_POST['txt'];
$country = $_POST['country'];
$passport= $_POST['passport'];
foreach($txtbox as $a => $b)
echo "$chkbox[$a] - $txtbox[$a] - $country[$a] - $passport[$a]";
That works fine, got it showing on my screen. Then I wanted to integrate it all in my extensive form, which I need to be sent off to my mail address... see my php example below (all the $_POST's there are additional). What would the 'foreach' code be to be able to send all the information from above mentioned dynamic rows to my mail address? And what would I have to add to my $message to get it visible? Thanks for your help.
$TripType = $_POST['TripType'];
$DepartureDay = $_POST['DepartureDay'];
$DepartureMonth = $_POST['DepartureMonth'];
$DepartureYear = $_POST['DepartureYear'];
$ReturnDay = $_POST['ReturnDay'];
$ReturnMonth = $_POST['ReturnMonth'];
$ReturnYear = $_POST['ReturnYear'];
$Adults = $_POST['Adults'];
$Children411 = $_POST['Children411'];
$Children03 = $_POST['Children03'];
foreach ($_POST['Check'] as $value) {$check_msg .= $value\n";}
$Comments = $_POST['Comments'];
$mail = $_POST['mail'];
$telephone = $_POST['telephone'];
$message = "Booking\n\nTripType: $TripType\n\nDepartureDay: $DepartureDay\nDepartureMonth: $DepartureMonth\nDepartureYear: $DepartureYear\n\nReturnDay: $ReturnDay\nReturnMonth: $ReturnMonth\nReturnYear: $ReturnYear\n\nAdults: $Adults\nChildren411: $Children411\nChildren03: $Children03\n $check_msg\nComments: $Comments\nmail: $mail\ntelephone: $telephone";
$xHeaders = "From: $mail\nX-Mailer: PHP/" . phpversion();
mail ("mymail#gmail.com", internet booking", $message, $xHeaders);
This should do what you want. Your HTML doesn't include a FORM or INPUT/submit so I'm guessing that they are there and working.
foreach($_POST['chk'] as $num => $value) {
$check_msg .= "$num = $value \n";
}
try:
$message = '';
foreach ($_POST as $k => $v) {
$message .= $k.': '.$v.'\n';
}
I'm trying to create a simple form which calculates the values in every input field which has subtotal at the start of the name attribute:
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript">
$(function(){
var qty = 0;
var price = 0;
var subtotal = 0;
var qty_r = [];
var price_r = [];
var subs_r = [];
var total = 0;
$('input[name^=qty]').each(function(index) {
qty_r[index] = $(this).val();
});
$('input[name^=price]').each(function(index){
price_r[index] = $(this).val();
});
var j = 0;
for(j = 0; j<=2; j++){
subs_r[j] = parseInt(price_r[j]) * parseInt(qty_r[j]);
}
$('input[name^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});
$('input[name^=qty]').keyup(function(){
var basis = $(this).attr("id");
var numbasis = basis.toString();
qty = $(this).val();
price = $('input[name=' + numbasis + ']').val();
subtotal = parseInt(qty) * parseInt(price);
$("#subtotal" + numbasis).val(subtotal);
This is the part where I'm having trouble:
$("input[name=subs]").each(function(index){
total = parseInt($(this).val()) + total;
$('#total').val(total);
});
});
});
</script>
And here's where the data which being calculated comes from:
<?php $products = array(array("prodname"=>"mais", "qty"=>5, "price"=>15), array("prodname"=>"strawberry", "qty"=>7, "price"=>25), array("prodname"=>"kambing", "qty"=>14, "price"=>3)); ?>
<table border="1">
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
<?php foreach($products as $key=>$prods){
?>
<tr>
<td><input type="text" name="prodname<?php echo $key; ?>" value="<?php echo $prods['prodname']; ?>"/></td>
<td><input type="text" id="<?php echo $key; ?>" name="qty<?php echo $key; ?>" value="<?php echo $prods['qty']; ?>"/></td>
<td><input type="text" name="<?php echo $key; ?>" id="price<?php echo $key; ?>" value="<?php echo $prods['price']; ?>"/></td>
<td><input type="text" name="subs" id="subtotal<?php echo $key; ?>" /></td>
</tr>
<?php } ?>
</table>
Total: <input type="text" id="total"/><br/>
The problem is that I'm always getting NaN as a result.
If you're getting NaN you're probably trying to parseInt something that has a return value of NaN. You can do
$("input[name=subs]").each(function(index) {
total = (parseInt($(this).val(), 10) || 0) + total;
$('#total').val(total);
});
Wich will always only add numbers to total.
Let's make that a possible answer, try using:
total = parseInt($(this).val()) + parseInt(total);
Also make sure $(this).val() has a proper value everywhere. If it's blank you will get NaN as a result. For almost any other you will get the right result: http://www.w3schools.com/jsref/jsref_parseInt.asp
It looks like you might be using the wrong selector to set the subtotal values you're using to do the final calculation. Shouldn't it be this:
$('input[id^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});