This is My HTML Code
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date"
value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]"
id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right"
id="txtUnit" oninput="calculate()" value="1" onkeypress="return
isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right"
id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary"
hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd"
class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;"
id="select">select</th>
<th style="width: 50px; text-align: center
!important;">Sl.No</th>
<th style="width: 125px; text-align: center
!important;">Date</th>
<th style="width: 175px; text-align: center
!important;">Service</th>
<th style="width: 80px; text-align: center
!important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal"
oninput="addTotal();" id="txtGrandTotal" readonly/>
</form>
This is My PHP code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount,
backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>
This is MY JAVASCRIPT CODE
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td><input type='checkbox'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td>"
+ date + "</td><td>"
+ amount + "</td><td>"
+ unit + "</td><td>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
Here I want to save whatever is generated from dynamically created table data to the database. I tried a lot but unable to do so. Am getting an error saying undefined index date amount etc. Here I want to generate id for every automatically generated table row but unable to figure out how to do so.
Is there any other solution for this ?
Thank in Advance.
Okay....
In my code I'm created a div with class data in which I put four inputs date,amount,unit and total.
I add plus and minus buttons in last for add/remove row.
by clicking plus button clone of previous row appear in last
On submit data of all input will be send to the submit URL.
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"])){
$value = '';
for ($i=0;$i<count($_POST['date']);$i++) {
$value .= '("'.$_POST["date"][$i].'","'.$_POST["amount"][$i].'","'.$_POST["unit"][$i].'","'.$_POST["total"][$i].'"),';
}
$value = rtrim($value,",");
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ".$value;
$result = mysqli_query($conn, $sql);
}
echo '
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><br />
<div class="container">
<h2>Vertical (basic) form</h2>
<form action="/action_page.php">
<div class="row data" divid="1">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Date</span>
<input type="text" class="form-control date" value="'.date('Y/M/d').'" id="date-1" placeholder="Enter date" name="date[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Amount</span>
<input type="text" class="form-control amount" data-id="1" value="0" id="amount-1" placeholder="Enter Amount" name="amount[0]" />
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Unit</span>
<input type="text" class="form-control unit" data-id="1" id="unit-1" value="0" placeholder="Enter Unit" name="unit[0]" />
</div>
</div>
<div class="col-md-2">
<div class="input-group">
<span class="input-group-addon">Total</span>
<input type="text" class="form-control total" id="total-1" readonly="readonly" name="total[0]" />
</div>
</div>
<div class="col-md-1">
<button class="btn btn-success btn-block plus" type="button" id="p-1">+</button>
<button class="btn btn-danger btn-block minus hide" type="button" id="m-1">-</button>
</div>
</div>
<div class="row"><div class="col-md-3"> </div></div>
<div class="row">
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">Grand Total</span>
<input type="text" class="form-control" value="0" id="g-total" readonly="readonly" name="g_total" />
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-default" name="save">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>';
?>
<script type="text/javascript">
$(document).on('change','.unit,.amount',function(e) {
id = parseInt($(this).attr("id").replace("unit-", "").replace("amount-",""));
get_total(id);
});
function get_total(id){
unit_d = parseInt($('#unit-'+id).val());
amount = parseInt($('#amount-'+id).val());
total = Math.ceil(amount*unit_d);
$('#total-'+id).val(total);
var g_total = 0;
jQuery('.total').each(function(){
g_total = g_total+parseInt($(this).val());
});
$('#g-total').val(g_total);
}
/****************************JS for add new row****************************/
$(document).on('click','.plus',function(e) {
var thisRow = $('.data').last(".data");
var newid = parseInt(thisRow.attr('divid'))+1;
var cid = parseInt(thisRow.attr('divid'));
var date = $('#date-'+cid).val();
var amount = $('#amount-'+cid).val();
var n_unit = $('#unit-'+cid).val();
var total = $('#total-'+cid).val();
if(date=="") $('#date-'+cid).addClass('error'); else $('#date-'+cid).removeClass('error');
if(amount=="") $('#amount-'+cid).addClass('error'); else $('#amount-'+cid).removeClass('error');
if(n_unit=="") $('#unit-'+cid).addClass('error'); else $('#unit-'+cid).removeClass('error');
if(total=="") $('#total-'+cid).addClass('error'); else $('#total-'+cid).removeClass('error');
if((date!="")&&(amount!="")&&(n_unit!="")&&(total!="")){
$('#date-'+cid+',#amount-'+cid+',#unit-'+cid).attr('readonly','readonly');
newRow = thisRow.clone(true).insertAfter(thisRow).find('input').val('').end().
find('.date').each(function(){
$(this).attr('id', 'date-'+newid);
$(this).attr('name','date['+(newid-1)+']');
$(this).val($('#date-'+cid).val());
$(this).removeAttr('readonly');
}).end().find('.amount').each(function(){
$(this).attr('id', 'amount-'+newid);
$(this).attr('name','amount['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.unit').each(function(){
$(this).attr('id', 'unit-'+newid);
$(this).attr('name','unit['+(newid-1)+']');
$(this).attr('data-id',newid);
$(this).val(0);
$(this).removeAttr('readonly');
}).end().find('.total').each(function(){
$(this).attr('id', 'total-'+newid);
$(this).attr('name','total['+(newid-1)+']');
$(this).val(0);
}).end().find('.plus').each(function(){
$(this).attr('id', 'p-'+newid);
$(this).attr('data-id', newid);
}).end().find('.minus').each(function(){
$(this).attr('id', 'm-'+newid);
}).end();
thisRow.next('.data').attr("divid",newid).addClass('child');
$('.minus').removeClass('hide');
$('.plus').addClass('hide');
$('#m-'+newid).addClass('hide');
$('#p-'+newid).removeClass('hide');
}
});
/****************************JS for add new row****************************/
/****************************JS for delete row****************************/
$('.minus').click(function(e) {
$(this).closest('.data').remove();
});
/****************************JS for delete row****************************/ </script>
Related
I am learning frontend and I face this problem to save data from Html to Mysql in Asp.Net Core:
I have Order Model
OrderDetails Model
and I made ViewModel
Html table coded to add Rows dinamicly
And i get project , supplier and Item by viewdata as select items
All above it was done But can not save the record!!
<link rel="stylesheet" href="~/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="~/lib/font-awesome/css/all.min.css">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="~/css/style.css">
<!-- container -->
<div class="container" >
<div style="align-items:self-end">
<input type="button" onclick="enabled()" value=" New Purchace Order" style="margin:10px 10px;" id="newOrder" class="btn btn-info" />
</div>
#* <div class="row bg-info m-1 block">
<div class="text-center col-md-8">
<h1> Purchace Order <span id="countpro"></span></h1>
</div>
</div>*#
<!-- Order Section -->
#*<form asp-action="Create">*#
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row bg-secondary m-1 block">
<div class="col-md-4 col-sm-12">
<div class="form-group">
<label asp-for="OrderNO" class="control-label"></label>
<input asp-for="OrderNO" id="poNO" class="form-control" />
<span asp-validation-for="OrderNO" class="text-danger"></span>
</div></div>
<div class="col-md-4 col-sm-12">
<div class="form-group">
<label asp-for="OrderDate" class="control-label"></label>
<input asp-for="OrderDate" id="poDate" class="form-control" />
<span asp-validation-for="OrderDate" class="text-danger"></span>
</div></div>
<div class="col-md-4 col-sm-12">
<div class="form-group">
<label asp-for="Status" class="control-label"></label>
<input asp-for="Status" id="status" class="form-control" />
<span asp-validation-for="Status" class="text-danger"></span>
</div></div>
<div class="col-md-6 col-sm-12">
<div class="form-group">
<label asp-for="ProjectId" class="control-label"></label>
<select asp-for="ProjectId" id="project" class ="form-control" asp-items="ViewBag.ProjectId"></select>
</div></div>
<div class="col-md-6 col-sm-12">
<div class="form-group">
<label asp-for="SupplierId" class="control-label"></label>
<select asp-for="SupplierId" id="supplier" class ="form-control" asp-items="ViewBag.SupplierId"></select>
</div></div>
<div class="form-group">
<label asp-for="Subject" class="control-label"></label>
<input asp-for="Subject" id="subject" placeholder="Enter Order Description ...." class="form-control" />
<span asp-validation-for="Subject" class="text-danger"></span>
</div>
</div>
<!-- End Order Section -->
<!-- Item Section -->
<div class="row bg-primary m-1 block">
<div class="col-md-5 col-sm-12">
<div class="form-group">
<label asp-for="ItemId" class="control-label"></label>
<select asp-for="ItemId" id="item" asp-placeholder="Select Item ...." class ="form-control" asp-items="ViewBag.ItemId"></select>
</div></div>
<div class="col-md-1 col-sm-12">
<div class="form-group">
<label asp-for="UnitId" class="control-label"></label>
<select asp-for="UnitId" id="unit" class ="form-control" asp-items="ViewBag.UnitId"></select>
</div></div>
<div class="col-md-1 col-sm-12">
<div class="form-group">
<label asp-for="Qty" class="control-label"></label>
<input asp-for="Qty" id="qty" class="form-control" onkeyup="getTotal()" onchange="getTotal()"/>
<span asp-validation-for="Qty" class="text-danger"></span>
</div></div>
<div class="col-md-1 col-sm-12">
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" id="price" class="form-control" onkeyup="getTotal()" onchange="getTotal()" />
<span asp-validation-for="Price" class="text-danger"></span>
</div> </div>
<div class="col-md-2 col-sm-12">
<div class="form-group">
<label asp-for="Total" class="control-label"></label>
<input asp-for="Total" id="total" class="form-control bg-danger text-center" disabled value="0" />
<span asp-validation-for="Total" class="text-danger"></span>
</div></div>
<div class="col-md-2 col-sm-12">
<label class="control-label">Add</label>
<button class="btn btn-success " onclick=" addRow();" id="addButton">
<i class="fas fa-plus"></i></button>
</div>
</div>
<!-- End Item Section -->
<!-- Table -->
<table class="table " style="width:100%;" id="tablPro">
<thead>
<tr>
<th>#</th>
<th style="width:30%;">Product/Service</th>
<th style="width:10%;">Unit</th>
<th style="width:10%;">Qty</th>
<th style="width:10%;">Price</th>
<th style="width:15%;">Total</th>
<th style="width:5%;"></th>
<th style="width:5%;"></th>
</tr>
</thead>
<tbody id="tablePro">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<!-- End Table -->
<!-- Total Section -->
#* <div class="row bg-teal m-1 block" id="divPrint">*#
<div class="totalcontainer">
<div class="col-md-3 col-sm-12">
<label asp-for="SubTotal" style="color:Black;" class="control-label"></label>
<input asp-for="SubTotal" id="subTotal" class="form-control" />
<span asp-validation-for="SubTotal" class="text-danger"></span>
</div>
<div class="col-md-3 col-sm-12">
<label asp-for="Vat" style="color:Black;" class="control-label"></label>
<input asp-for="Vat" id="vat" class="form-control" />
<span asp-validation-for="Vat" class="text-danger"></span>
</div>
<div class="col-md-3 col-sm-12">
<label asp-for="GrandTotal" style="color:Black;" class="control-label"></label>
<input asp-for="GrandTotal" id="grandTotal" class="form-control" />
<span asp-validation-for="GrandTotal" class="text-danger"></span>
</div>
<div class="text-center">
<input type="submit" value=" + Save Purchace Order" id="saveBtn" style="margin:10px 10px;" class="btn btn-primary" />
</div>
</div>
<!-- End Total Section -->
<hr />
<!-- End Createor Section -->
<div class="row block">
<div class="col-md-3 col-sm-12">
<div class="form-group">
<label asp-for="CreatedBy" style="color:Black;" class="control-label"></label>
<input asp-for="CreatedBy" class="form-control" />
<span asp-validation-for="CreatedBy" class="text-danger"></span>
</div> </div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<label asp-for="TimeStamp" style="color:Black;" class="control-label"></label>
<input asp-for="TimeStamp" class="form-control" />
<span asp-validation-for="TimeStamp" class="text-danger"></span>
</div> </div>
</div>
<!-- End Createor Section -->
#* </form>*#
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/js/addRow.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/adminlte/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="~/lib/font-awesome/js/all.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
// $('#saveBtn').click(function() {
// var data = $('input').serialize();
// $.post(url, data, function(data) {
// console.log(data);
// });
//});
$(function () {
$("#saveBtn").click(function () {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "CreatePos/Create",
data: "{'poNo':'" + $("#poNO").val() +
"', 'poDate':'" + $("#poDate").val() +
"', 'status':'" + $("#status").val() +
"', 'project':'" + $("#project").val() +
"', 'supplier':'" + $("#supplier").val() +
"', 'Subject':'" + $("#Subject").val() +
"', 'item':'" + $("#item").val() +
"', 'unit':'" + $("#unit").val() +
"', 'qty':'" + $("#qty").val() +
"', 'total':'" + $("#total").val() +
"', 'subTotal':'" + $("#subTotal").val() +
"', 'vat':'" + $("#vat").val() +
"', 'grandTotal':'" + $("#grandTotal").val() + "'}",
async: false,
success: function (response) {
$("#poNO").val("");
$("#poDate").val("");
$("#status").val("");
$("#project").val("");
$("#supplier").val("");
$("#Subject").val("");
$("#item").val("");
$("#unit").val("");
$("#qty").val("");
$("#total").val("");
$("#subTotal").val("");
$("#vat").val("");
$("#grandTotal").val()
alert("record has been saved in database");
},
error: function () {
console.log("there is some error");
}
});
});
});
</script>
}
And her is the Script File
var value = document.getElementById('item');
var getItem = value.options[value.selectedIndex].text;
var unitValue = document.getElementById('unit');
var getUnit = unitValue.options[unitValue.selectedIndex].text;
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
var total = document.getElementById('total').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length);
var x = newRow.rowIndex - 1;
var editBtn =`<button class="btn btn-info" id="editRow">
<i class="fas fa-edit"></i>
</button>` ;
var deleteBtn =`<button class="btn btn-danger" onclick="deleteRow(this)">
<i class="fas fa-trash"></i>
</button>` ;
//defination of row cells
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
var cell5 = newRow.insertCell(4);
var cell6 = newRow.insertCell(5);
var cell7 = newRow.insertCell(6);
var cell8 = newRow.insertCell(7);
// Push row Values into tabel Body
cell1.innerHTML = x++;
cell2.innerHTML = getItem;
cell3.innerHTML = getUnit;
cell4.innerHTML = qty;
cell5.innerHTML = price;
cell6.innerHTML = total;
cell7.innerHTML = editBtn;
cell8.innerHTML = deleteBtn;
}
function getTotal() {
if (price.value != '') {
let result = price.value * qty.value;
total.value = result;
total.style.background = '#040';
let vatPercentage = 0.15;
let subtotal = document.getElementById('subTotal');
let vat = document.getElementById('vat');
let grandTotal = document.getElementById('grandTotal');
subtotal.value = total.value;
vat.value = subtotal.value * vatPercentage;
grandTotal.value = +vat.value + +subtotal.value;
}
else {
total.value = '';
total.style.background = '#a00d02';
}
}
Finally This is the controller
POST: CreatePos/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("OrderId,OrderNO,OrderDate,Subject,Status,CreatedBy,TimeStamp,ProjectId,SupplierId,ItemId,UnitId,Qty,Price,Total,SubTotal,Vat,GrandTotal")] CreatePoModel createPoModel)
{
if (ModelState.IsValid)
{
_context.Add(createPoModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["ProjectId"] = new SelectList(_context.Projects, "ProjectId", "ProjectName", createPoModel.ProjectId);
ViewData["SupplierId"] = new SelectList(_context.Suppliers, "SupplierId", "SupplierName", createPoModel.SupplierId);
ViewData["ItemId"] = new SelectList(_context.PoItems, "ItemId", "ItemName", createPoModel.ItemId);
ViewData["UnitId"] = new SelectList(_context.Units, "UnitId", "UnitCode", createPoModel.UnitId);
return View(createPoModel);
}
Please Consider that I am beginner still learning: (
I want to make some forms in a div, and in this form, there is requirement that some form can add some input text like add a row in a table and in this div can add another div to add form to write data too. I'm already success to add data but it only works in a form because my button only can submit the data if I put it in a form. I'm new in using PHP, HTML, and JavaScript, so when I was writing code, i'm still in learning too and search many website to solve this but i'm just get the answer to submit only a form.
please help me, i'm very thankful for your response
<div id="myproyek">
<div id="formtrigger" class="content">
<form id="tableToModify" name="code" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<td>Create Url</td>
<td>:</td>
<td><input type="text" name="nameURL" id="nameURL" placeholder="URL"></td>
<span class="error"><?php echo $nameURLErr;?></span>
</div>
<div class="form-group">
<td>Parameter</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="key" name="key" placeholder="Key">
<span><?php echo $keyErr ?></span>
<input type="text" id="value" name="value" placeholder="Value">
<span><?php echo $valueErr ?></span>
</div>
</form>
<input type="button" onclick="addRow()" value="Create Row" />
<div>
<label><input type="radio" name="colorRadio" value="asynchronous">Asynchronous</label>
<label><input type="radio" name="colorRadio" value="synchronous">Synchronous</label>
<div class="asynchronous box " style="display: none" >
<form id="tableAscyToModify" >
<div class="form-group">
<td>Callback Url</td>
<td>:</td>
<td><input type="text" name="createurl" placeholder="Callback URL" onfocus="this.placeholder = ''" onblur="this.placeholder = 'URL'" value="<?php echo $asyncValue?>"></td>
<span><?php echo $asyncURLErr ?></span>
</div>
<div class="form-group">
<td>Format Response</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="item-code" name="createurl" placeholder="Key">
<span><?php echo $asyncKeyErr ?></span>
<input type="text" id="item-code" name="createurl" placeholder="Value">
<span><?php echo $asyncValueErr ?></span>
</div>
</form>
<input type="button" onclick="createRowAsyc()" value="Create Row" />
</div>
<div class="synchronous box " style="display: none">
<form id="tableSyncToModify" >
<div class="form-group">
<td>Format Response</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="item-code" name="createurl" placeholder="Key">
<input type="text" id="item-code" name="createurl" placeholder="Value">
</div>
</form>
<input type="button" onclick="createRowSync()" value="Create Row" />
</div>
</div>
</form>
</div>
<button name="submit" id="submit">Submit</button>
// i think button should be here because i want to submit all my form
</div>
Here is my PHP Code
<?php
// define variables and set to empty values
$nameURLErr = $keyErr = $valueErr = $asyncURLErr = $asyncKeyErr = $asyncValueErr = $syncURLErr = $syncKeyErr = $syncValueErr = "";
$nameURL = $key = $value = $asyncURL = $asyncKey = $asyncValue = $syncURL = $syncKey = $syncValue = "";
if (isset($_POST['value'])) {
if (empty($_POST["nameURL"])) {
$nameURLErr = "URL is required";
} else {
$nameURL = test_input($_POST["nameURL"]);
// check if name only contains letters and whitespace
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$nameURL)) {
$nameURLErr = "Only letters and white space allowed";
}
}
if (empty($_POST["key"])) {
$keyErr = "Key is required";
} else {
$key = test_input($_POST["key"]);
}
if (empty($_POST["value"])) {
$valueErr = "Value is required";
} else {
$value = test_input($_POST["value"]);
}
if (empty($_POST["asyncURL"])) {
$asyncURLErr = "URL is required";
} else {
$asyncURL = test_input($_POST["asyncURL"]);
// check if name only contains letters and whitespace
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$asyncURL)) {
$asyncURLErr = "Only letters and white space allowed";
}
}
if (empty($_POST["asyncKey"])) {
$asyncKeyErr = "Key is required";
} else {
$asyncKey = test_input($_POST["asyncKey"]);
}
if (empty($_POST["asyncValue"])) {
$asyncValueErr = "Value is required";
} else {
$asyncValue = test_input($_POST["asyncValue"]);
}
$fp = fopen('data.html', 'a');
$data = '<p> URL : '.$nameURL. '</p>'.
'<p>Key : ' . $key . '<br>Value : '. $value . '</p>' .
'<p>Async URL : ' . $asyncURL . '</p>' .
'<p>Key : ' . $asyncKey . '<br>Value : ' . $asyncValue . '</p>';
;
fwrite($fp, $data);
fclose($fp);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my Javascript code
function addRow () {
document.querySelector('#tableToModify').insertAdjacentHTML(
'beforeend',
`<form>
<div class="form-group">
<input type="text" name="name" value="" placeholder="Key" />
<input type="text" name="value" value="" placeholder="Value" />
<input type="button" value="-" onclick="removeRow(this)">
</div>
</form>`
)
}
function createRowAsyc() {
document.querySelector('#tableAscyToModify').insertAdjacentHTML(
'beforeend',
`<div class="form-group">
<input type="text" name="name" value="" placeholder="Key"/>
<input type="text" name="value" value="" placeholder="Value"/>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function createRowSync() {
document.querySelector('#tableSyncToModify').insertAdjacentHTML(
'beforeend',
`<div class="form-group">
<input type="text" name="name" value="" placeholder="Key"/>
<input type="text" name="value" value="" placeholder="Value"/>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function removeRow (input) {
input.parentNode.remove()
}
I expect the output is all the data is write in all the form, but if i put the button right in last div code, but there is nothing to change.
If i put button in
<form id="tableToModify">
</form>
data is submitted only in this data and successful submitted in text.html
Or do you have some suggestion, how i manage my form template
You can get your forms into one by using FormData()
Here we have a button element outside all forms, this will be our trigger to submit:
<div>
<form id="form-one">
<!-- the form -->
</form>
<form id="form-two">
<!-- the form -->
</form>
<button type="button" id="submit-data">
<span>Submit all forms!</span>
</button>
</div>
then in your JavaScript we collect all the FormData's into one "mothership" FormData by using loops, triggered by the button click
document.addEventListener('click', function()
{
let formData = new FormData(),
formOne = new FormData(document.getElementById('form-one')),
formTwo = new FormData(document.getElementById('form-two'));
for (let pair of formOne.entries())
{
formData.append(pair[0], pair[1])
}
for (let pair of formTwo.entries())
{
formData.append(pair[0], pair[1])
}
}, false)
This is my HTML and javascript script
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date" id="date" value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount" id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit" class="text-right" id="txtUnit" oninput="calculate()" value="1" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal" class="text-right" id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary" hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd" class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;" id="select">select</th>
<th style="width: 50px; text-align: center !important;">Sl.No</th>
<th style="width: 125px; text-align: center !important;">Date</th>
<th style="width: 175px; text-align: center !important;">Service</th>
<th style="width: 80px; text-align: center !important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal" oninput="addTotal();" id="txtGrandTotal" readonly/>
This is my javascript code
<div id="ta">
<script type="text/javascript">
var lclCount=0;
$("#tableAdd").click(function(){
var sl_no = ($('#tabledata tr').length) - 1;
lclCount++;
sl_no++;
var date = $("#date").val();
var amount = $("#txtAmount").val();
var unit = $("#txtUnit").val();
var total = $("#txtTotal").val();
var markup = "<tr><td class='mar'><input type='checkbox' class='chk'
name='record' id='"+ lclCount +"'></td><td name='slno' class='slno' id
='slno-"+sl_no+"'>"
+ sl_no + "</td><td class='date1' name='date'>"
+ date + "</td><td name='amount'>"
+ amount + "</td><td name='unit'>"
+ unit + "</td><td name='total' id='txtTot-"+lclCount+"'>"
+ parseFloat(total).toFixed(2) + "</td></tr>";
$("#tabledata").append(markup);
addTotal();
refreshAdd();
});
</script>
<!-- <div class="page-break"></div> -->
</div>
<input type="submit" name="save" value="save">
and last here is my php code
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$date = $_POST["date"];
$amount = $_POST["txtAmount"];
$unit = $_POST["txtUnit"];
$total = $_POST["txtTotal"];
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
?>
Here I want to save the that generate from dynamically created table data to the database but I am tried a lot but not able to save to the database getting an error like undefined index date amount etc. here I want generate id for every row that for automatically generated table row but not getting how to generate is there any other solution foe this guys. Thank in Advance.
Here's how you can do it, by using "arrays" on the inputs name, by defining the inputs name like arrays eg: "date" will be "date[]"
<form method="POST" action="backend/backup.php">
<div class="box-body col-sm-12">
<input type="hidden" name="txtSlNo" id="txtSlNo" value="1">
<div class="col-sm-2">
<label for="Date" class="control-label">Date:</label>
<input type="text" class="text-right" name="date[]" id="date" value="<?php echo date(" Y/M/D ")?>">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Amount:</label>
<input type="text" size="7" class="text-right" name="txtAmount[]" id="txtAmount" oninput="calculate()" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Unit:</label>
<input type="text" size="7" name="txtUnit[]" class="text-right" id="txtUnit" oninput="calculate()" value="1" onkeypress="return isNumber(event);">
</div>
<div class="col-sm-1">
<label for="name" class="control-label">Total:</label>
<input type="text" size="7" name="txtTotal[]" class="text-right" id="txtTotal" oninput="calculate();" oninput="addTotal();" readonly>
</div>
<div class="col-sm-2">
<br>
<!-- <button name="add" id="add" class="btn btn-primary" hidden="hidden">Add</button> -->
</div>
<div class="col-sm-2">
<input type="button" value="add" name="tableAdd" id="tableAdd" class="btn btn-primary add add1">
</div>
</div>
<div class="col-xs-12">
<table id="tabledata" name="tabledata">
<thead>
<tr>
<th style="width: 50px; text-align: center !important;" id="select">select</th>
<th style="width: 50px; text-align: center !important;">Sl.No</th>
<th style="width: 125px; text-align: center !important;">Date</th>
<th style="width: 175px; text-align: center !important;">Service</th>
<th style="width: 80px; text-align: center !important;">Charge</th>
<th style="width: 80px;">Amount</th>
<th style="width: 80px;">Unit</th>
<th style="width: 80px;">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button type="button" id="delete-row" class="delete-row">Delete Row</button>
<button class="print" onclick="myFunction()">Print this page</button>
<br>
<label class="GrandTotalLabel" id="GrandTotalLabel">GRAND TOTAL</label>
<input type="text" name="txtGrandTotal" value="00.00" class="txtGrandTotal" oninput="addTotal();" id="txtGrandTotal" readonly/>
And on the server side, you iterate on the received arrays:
<?php
$servername = "localhost";
$username = "1234";
$password = "";
$dbname = "tad";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["save"]))
{
$numberOfRows = count($_POST['date']); // get the number of rows
for ($i = 0; $i < $numberOfRows; $i++) {
$date = $_POST["date"][$i];
$amount = $_POST["txtAmount"][$i];
$unit = $_POST["txtUnit"][$i];
$total = $_POST["txtTotal"][$i];
$sql = "INSERT INTO backup_master (backup_date, backup_amount, backup_unit, backup_total) VALUES ('$date', '$amount', '$unit', '$total')";
$result = mysqli_query($conn, $sql);
}
}
?>
This is my html ajax and js code, it's dynamic input field form
i want to insert multiple data into mysql database following these column "pro" "des" "qty" "price" "sub_total" . "qty" and "price" used auto sum value to "sub_total" input field
please see my full html code then Please write a php code for me .
Last time i was failed many time to do it.
so please help me
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="invoice system, php invoice script, invoice script, pro invoice maker, free php invoice/billing script, php Invoice software, php invoice generator script, invoice script open source, invoice generator php script, invoice script in php, javascript invoice script, invoice maker php script, php invoice script tutorial">
<meta name="keywords" content="invoice system, php invoice script, invoice script, pro invoice maker, free php invoice/billing script, php Invoice software, php invoice generator script, invoice script open source, invoice generator php script, invoice script in php, javascript invoice script, invoice maker php script, php invoice script tutorial">
<meta name="author" content="http://tanbhirhossain.me">
<title>AFOJAL MINI MARKET</title>
<!-- Bootstrap -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,200' rel='stylesheet' type='text/css'>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link href="css/admin.css" rel="stylesheet">
<!-- Script -->
<script src="js/jquery.min.js"></script>
<script src="js/wayfinder.js" ></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script>
$(document).ready(function() {
jQuery('.load-animate').waypoint({
triggerOnce: true,
offset: '80%',
handler: function() {
jQuery(this).addClass('animated fadeInUp');
}
});
});
</script>
</head>
<body>
<!-- Static navbar -->
<div role="navigation" class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" data-toggle="collapse"
data-target=".navbar-collapse" class="navbar-toggle collapsed">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Afojal Mini Market Invoice System</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">
Hello
muni <span class="caret"></span>
</a>
<ul role="menu" class="dropdown-menu account-menu">
<li> <i class="fa fa-user"></i> My Account </li>
<li class="divider"></li>
<li style="background: #e67e22; color:#fff"> <a class="logout" href="logout.php"> <i class="fa fa-power-off"></i> Signout</a> </li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">
<!-- Begin page content -->
<div class="container content-invoice">
<form action="invoice.php" id="invoice-form" method="post" class="invoice-form" role="form" novalidate>
<div class="load-animate">
<input type="hidden" value="" name="data[id]">
<div class='row'>
<div class='col-xs-8 col-sm-8 col-md-8 col-lg-8'>
<h1 class="title">PHP Invoice System</h1>
</div>
<div class='col-xs-4 col-sm-4 col-md-4 col-lg-4'>
<input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-top form-control"/>
</div>
</div>
<input id="currency" type="hidden" value="RM">
<div class='row'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
<th width="15%">Product</th>
<th width="38%">Description</th>
<th width="15%">Price</th>
<th width="15%">Quantity</th>
<th width="15%">Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><input type="text" data-type="productCode" name="data[Invoice][pro][]" id="ipro_1" class="form-control autocomplete_txt" autocomplete="off"></td>
<td><input type="text" data-type="productName" name="data[Invoice][des][]" id="ides_1" class="form-control autocomplete_txt" autocomplete="off"></td>
<td><input type="number" name="data[Invoice][price][]" id="price_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="number" name="data[Invoice][qty][]" id="quantity_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
<td><input type="number" name="data[Invoice][sub_total][]" id="total_1" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
<button class="btn btn-danger delete" type="button">- Delete</button>
<button class="btn btn-success addmore" type="button">+ Add More</button>
</div>
</div>
<div class='row'>
<div class='col-xs-12 col-sm-8 col-md-8 col-lg-8'>
<h3>Notes: </h3>
<div class="form-group">
<textarea class="form-control txt" rows='5' name="data[notes]" id="notes" placeholder="Your Notes"></textarea>
</div>
<div class='form-group text-center'>
<input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-btm"/>
</div>
</div>
<div class='col-xs-12 col-sm-4 col-md-4 col-lg-4'>
<span class="form-inline">
<div class="form-group">
<label>Subtotal: </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="data[subTotal]" id="subTotal" placeholder="Subtotal" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Tax: </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="data[tax]" id="tax" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Tax Amount: </label>
<div class="input-group">
<input value="" type="number" class="form-control" name="data[taxAmount]" id="taxAmount" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
<div class="input-group-addon">%</div>
</div>
</div>
<div class="form-group">
<label>Total: </label>
<div class="input-group">
<div class="input-group-addon currency">$</div>
<input value="" type="number" class="form-control" name="data[totalAftertax]" id="totalAftertax" placeholder="Total" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
</span>
</div>
</div>
<div class="clearfix"></div>
<div class='row'>
<div class='col-xs-12 col-sm-6 col-md-6 col-lg-6 text-center'>
</div>
</div>
</div>
</form>
</div>
<script src="js/jquery-ui.min.js"></script>
<script src="js/ajax.js"></script>
<script>
$('.submit_btn').on('click', function(){
$(this).button('loading');
});
$(document).ready(function(){
$('.currency').html( $('#currency').val() );
});
$('#clientCompanyName').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'customerName'
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[1],
value: code[1],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$(this).val(names[1]);
getClientAddress(names[0]);
}
});
function getClientAddress(id){
$.ajax({
url: "ajax.php",
method: 'post',
data:{id:id, type:'clientAddress'},
success: function(result){
$("#clientAddress").html(result);
}
});
}
</script>
<div class="clearfix"></div>
<footer class="footer">
<div class="container-fluid">
<!-- <p class="text-center">© Copyright by Smart Tutorials </p> -->
</div>
</footer>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
</body>
</html>
my php code was:
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "inv");
if(isset($_POST["pro"]))
{
$item_name = $_POST["pro"];
$item_code = $_POST["des"];
$item_des = $_POST["qty"];
$item_price = $_POST["price"];
$subtotal = $_POST["sub_total"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
$item_des_clean = mysqli_real_escape_string($connect, $item_des[$count]);
$item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
$subtotal_clean = mysqli_real_escape_string($connect, $subtotal[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_des_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO sell(pro, des, qty, price, sub_total)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_des_clean.'", "'.$item_price_clean.'", "'.$subtotal_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}
else
{
echo 'All Fields are Required';
}
}
?>
You will get your post data in $_POST['data']['Invoice'] array so change your script like :
//insert.php
$connect = mysqli_connect("localhost", "root", "", "inv");
if(isset($_POST['data']['Invoice']['pro']))
{
$item_name = $_POST['data']['Invoice']['pro'];
$item_code = $_POST['data']['Invoice']["des"];
$item_des = $_POST['data']['Invoice']["qty"];
$item_price = $_POST['data']['Invoice']["price"];
$subtotal = $_POST['data']['Invoice']["sub_total"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
$item_des_clean = mysqli_real_escape_string($connect, $item_des[$count]);
$item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
$subtotal_clean = mysqli_real_escape_string($connect, $subtotal[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_des_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO sell(pro, des, qty, price, sub_total)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_des_clean.'", "'.$item_price_clean.'", "'.$subtotal_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}
}
There are three files
1.street_master.php 2.street.php 3.streetdelete.php
street_master.php has form for adding new street(streetname,streetcode) when submit is pressed using ajax call new street is added and and the street list from the database are printed in table format( with individual delete option delete is done by streetdelete.php file ) on the same page that is street_master.php .but delete option is not working. actually form is not submitting which redirect to streetdelete.php
streetmaster.php
<html>
<?php include 'conf.php'; ?>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.12.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function showUser()
{
var n1=document.getElementById('scode').value;
var n2=document.getElementById('sname').value;
var n3=document.getElementById('desc').value;
var n4=document.getElementById('ward').value;
if (n1 == null || n1 == "" )
{
alert('fill street code ');
}
else if( n2 == null || n2 == "" ) {
alert('fill street name');
}
else
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
var q="?v1="+n1;
q+="&v2="+n2;
q+="&v3="+n3;
q+="&v4="+n4;
xmlhttp.open("GET","street.php"+q,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<center>
<h2>Street Master</H2>
</CENTER>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2">Street code </label>
<div class="col-sm-1">
<input type="number" class="form-control" name="scode" id="scode" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"> Street name</label>
<div class="col-sm-2"> <input type="text" class="form-control" name="sname" id="sname" required> </div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"> Description</label>
<div class="col-sm-2"> <input type="text" class="form-control" name="desc" id="desc" > </div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ward num"> Ward No </label>
<div class="col-sm-2">
<select name="ward" id="ward" class="form-control">
<option value="">chose the ward</option>
<?php
$s="select WardNo from ward";
$result=$con->query($s);
while($row = $result->fetch_assoc())
{
echo "<option value='$row[WardNo]'> ward $row[WardNo]</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-2"> <input type="button" class="form-control" value="submit" onClick="showUser()"> </div>
</div>
</form>
<div id="txtHint"></div>
</body>
</html>
street.php
<?php
$q =$_GET['v1'];
$q1 =$_GET['v2'];
$q2 =$_GET['v3'];
$q3 =$_GET['v4'];
/
include 'conf.php';
if($con)
{
$sql="insert into areacodemaster values('$q','$q1','$q3')";
$con->query($sql);
$s="select * from areacodemaster";
$result=$con->query($s);
echo "
<head>
<link rel='stylesheet' href='scroll.css'>
<script src='scroll.js'></script>
</head>
<body><center>
<table class='scroll'>
<thead>
<tr>
<th>Street_code</th>
<th width='70%'>Street_Name</th>
<th>Ward_Number</th>
<th>delete</th>
</tr>
</thead> ";
echo "
<tbody> ";
while($row = $result->fetch_assoc())
{
echo "
<tr>
<form action='streetdelete.php' method='post'>
<td>".$row['Areacode']."</td>
<td>".$row['Areaname']."</td>
<td>".$row['WardNo']."</td>
<td><input type='hidden' name='ac' value='$row[Areacode]'>
<td><input type='submit' value='Delete'></a></td>
</form>
</tr>";
}
echo "
</tbody>
</table></center>
</body> ";
}
?>
streetdelete.php
<?php
$g=$_POST['ac'];
include 'conf.php';
$sq="delete from areacodemaster where Areacode='$g'";
$con->query($sq);
echo "<script type='text/javascript'>alert('Deleted'); </script>";
?>
but if we run street.php alone form is submitting to streetdelete.php
Your whole code is in a mess and it need to be more organized,
The basics mistakes you have done:
1- You are adding new page each time new street is being shown, and that because you are mixing the server side page with the search page and to fix that you have to separate them, so a page for searching and another for showing.
2- It's better to have one core Ajax function to deal with all requests and then you can process the searching actions and deleting actions through Ajax, in this case you will not need to use a form for deleting and the problem will be solved, OR since you are including Jquery to your project then there is no need to have your own Ajax core function because Jquery has done that for you so you can call an Ajax request any place you want with your preferred parameters.
So your code will be as follow:
First page: streets.php (the main page which shows existing streets)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.12.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function deleteUser(streetCode){
$.ajax({
type: "POST",
url: "deletestreet.php",
data: {ac: streetCode},
success: function( msg ){$("#" + streetCode ).remove();alert("Deleted");}
});
}
function showUser(){
var n1 = $("#scode").val();
var n2 = $("#sname").val();
var n3 = $("#desc").val()
var n4 = $("#ward").val();
if (n1 == null || n1 == "" ){
alert('fill street code ');
}
else if( n2 == null || n2 == "" ){
alert('fill street name');
}
else{
$.ajax({
type: "POST",
url: "searchstreet.php",
data: {v1: n1, v2: n2, v3: n3, v4: n4},
success: function( msg ){$("#txtHint").html(msg);}
});
}
</script>
</head>
<body>
<center><h2>Street Master</h2></center>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2">Street code</label>
<div class="col-sm-1">
<input type="number" class="form-control" name="scode" id="scode" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Street name</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="sname" id="sname" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Description</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="desc" id="desc" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ward num">Ward No</label>
<div class="col-sm-2">
<select name="ward" id="ward" class="form-control">
<option value="">chose the ward</option>
<?php
$s="select WardNo from ward";
$result=$con->query($s);
while($row = $result->fetch_assoc()){
echo "<option value='$row[WardNo]'> ward $row[WardNo]</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"> </div>
<div class="col-sm-2">
<input type="button" class="form-control" value="submit" onClick="showUser()">
</div>
</div>
</form>
<div id="txtHint"></div>
</body>
</html>
Page 2: searchstreet.php
<?php
$q = $_GET['v1'];
$q1 =$_GET['v2'];
$q2 =$_GET['v3'];
$q3 =$_GET['v4'];
include 'conf.php';
if($con){
$sql = "insert into areacodemaster values('$q','$q1','$q3')";
$con->query($sql);
$s = "select * from areacodemaster";
$result=$con->query($s);
echo "
<center>
<table class='scroll'>
<thead>
<tr>
<th>Street_code</th>
<th width='70%'>Street_Name</th>
<th>Ward_Number</th>
<th>delete</th>
</tr>
</thead>
<tbody>";
while($row = $result->fetch_assoc()){
echo "
<tr id='".$row['Areacode']."'>
<td>".$row['Areacode']."</td>
<td>".$row['Areaname']."</td>
<td>".$row['WardNo']."</td>
<td><input type='button' value='Delete' onclick=deleteUser('".$row['Areacode']."')></td>
</tr>";
}
echo"
</tbody>
</table>
</center>";
}
deletestreet.php
<?php
$g = $_POST['ac'];
include 'conf.php';
$sq = "delete from areacodemaster where Areacode='$g'";
$con->query($sq);
?>