Ajax not working on multiple inserts - CI - javascript

I want to save multiple data in one go using codeigniter and then on success load the data on my datatable wihtout refreshing the whole page. I am able to do this successfully if I use modal and insert a single value but when I try to save multiple values, it doesn't work. I produce my input boxes on button click. Below are my codes:
CONTROLLER
public function add_multiple_orders(){
$dataset=[];
$item_name=$this->input->post('m_item_name');
$quantity=$this->input->post('m_quantity');
$amount=$this->input->post('m_amount');
$order_comment=$this->input->post('m_order_comment');
$branch_name=$this->input->post('m_branch_name');
$date_added=$this->input->post('m_date_added');
for($i=0;$i<sizeof($item_name);$i++){
$dataset[$i]=array(
'date_added'=>$date_added,
'item_name'=>$item_name[$i],
'quantity'=>$quantity[$i],
'amount'=>$amount[$i],
'ordered_by'=>$this->session->userdata['username'],
'order_status'=>'ordered',
'order_comment'=>$order_comment[$i],
'branch_name'=>$branch_name
);
}
$result=$this->sales_model->insert_mult_orders($dataset);
}
VIEW
<a name="mult_page">
<button class="btn btn-info" data-toggle="collapse" data-target="#add_multiple" style="margin-left: 20px;">Add Multiple Orders</button>
<div class="collapse" id="add_multiple" style="width: 95%; margin: 0 auto; margin-top: 10px;">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body">
<form class="form_mult_ordrs form-inline" method="post">
<div class="form-group">
<label for="m_date_added">Date</label>
<input type="date" name="m_date_added" required>
</div>
<div class="form-group">
<label for="m_branch_name" class="control-label">Branch Name</label>
<select name="m_branch_name" class="form-control">
<option value="superdome">Superdome</option>';
<option value="seaside">Sea Side</option>
<option value="robinsons">Robinsons</option>
</select>
</div>
<div class="btn btn-warning pull-right" onclick="add_new_row()">Add more</div>
<hr>
<div style="font-weight: bold;">Total Php <input type="text" id="total_result" placeholder="0.00" class="form-control"></div>
<br>
<table id="mult_ord_tbl" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th class="ui-help-center">Item Name</th>
<th class="ui-help-center">Quantity</th>
<th class="ui-help-center">Amount</th>
<th class="ui-help-center">Comment</th>
<th class="ui-help-center">Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="item_name[]" class="form-control">
<?php foreach($items as $item){
echo '<option value"='.$item->item_name.'">'.$item->item_name.'</option>';
} ?>
</select>
</td>
<td><input type="text" name="m_quantity[]" placeholder="Quantity"></td>
<td><input type="text" name="m_amount[]" id='m_amount[]' placeholder="Amount" onblur="total_values()"></td>
<td><input type="text" name="m_order_comment[]" placeholder="Commment"></td>
<td>
<button class="btn btn-danger" onclick="delete_row(this)"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
</tbody>
</table>
<tr>
<td colspan="12">
<button id="btn_mult_ordrs" class="btn btn-success" onclick="save_mult_ordrs()" value="">Submit All</button>
</td>
</tr>
</form>
</div> <!-- end of panel body -->
<div class="panel-footer">
footer
</div>
</div> <!-- end of panel primary -->
</div> <!-- end of column 12 -->
</div> <!-- end of row -->
</div> <!-- end of collapse -->
<script type="text/javascript">
$(document).ready(function(){
$('#table_id').DataTable({
"order":[[0,"desc"]]
});
});
function save_mult_ordrs(){
if(confirm("Are you done?")){
var url="<?php echo site_url('sales/add_multiple_orders')?>";
add_new_row();
// $("#form_mult_ordrs").submit();
$.ajax({
url:url,
type:"POST",
data:$('#form_mult_ordrs').serialize(),
datatype:"JSON",
success:function(data)
{
alert('All data has been saved.');
location.reload();
},
error:function(jqXHR, textStatus, errorThrown){
alert('Error in saving.');
}
});
}
}
function add_new_row(){
var arrTables = document.getElementById('mult_ord_tbl');
var oRows = arrTables.rows;
var numRows = oRows.length;
var newRow = document.getElementById('mult_ord_tbl').insertRow( numRows );
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);
cell1.innerHTML = "<tr><td><select name='m_item_name[]' class='form-control'>" +
<?php
foreach($items as $item){
echo ('"<option value=\"'.$item->item_name.'\">'.$item->item_name.'</option>"+');
}
?>
+ "</select></td>";
cell2.innerHTML="<td height='5'><input type='text' name='m_quantity[]' placeholder='Quantity'></td>";
cell3.innerHTML="<td height='5'><input type='text' name='m_amount[]' placeholder='Amount' onblur='total_values()'></td>"
cell4.innerHTML="<td height='5'><input type='text' name='m_order_comment[]' placeholder='Comment'></td>";
cell5.innerHTML="<td><button class='btn btn-danger' onclick='delete_row(this)''><i class='glyphicon glyphicon-remove'></i></button></td></tr>";
}
</script>
MODEL
public function insert_mult_orders($data){
$this->db->insert_batch('piercapitan.sls_ordrs',$data);
return $this->db->affected_rows();
}
Your help is immensely appreciated.

Never mind guys. I found what's wrong. It's my form id! I somehow placed the name on the class and not on the id.
<form class="form_mult_ordrs form-inline" method="post">
It should have been:
<form id="form_mult_ordrs" class="form-inline" method="post">

Related

AngularJS ng-model cannot bind input value

i have an input into my page and it's value is changing by + and - buttons,
this input contain the directive ng-model to pass it's value to angular controller js file
and there is a button to submit the input value inside MYSQL database
the issue is that every time i press the submit button the value inserted into database returns zero value
How can i assign the value of the input which changes by the buttons to the ng-model??
The index.php file :
<!-- October Evaluation Start -->
<div class="row">
<div class="card shadow mb-4" style="width: 900px;">
<div class="card-header py-3">
<div class="row">
<div class="col">
<h6 class="m-0 font-weight-bold text-primary">October evaluation</h6>
</div>
<div class="col"><button id="plus11" class="btn btn-info text-right">Add new</button>
</div>
</div>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="exampleFormControlSelect1">select user</label>
<select class="form-control" id="exampleFormControlSelect1" ng-model="gid">
<?php
$con = mysqli_connect("localhost","root","","users");
$sql = mysqli_query($con, "SELECT name From myusers");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['name'] ."'>" .$row['name'] ."</option>" ;
}
?>
</select>
</div>
<br>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Evaluation</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-danger btn-number" data-type="minus" data-field="quant[2]">
<span><i class="fas fa-minus"></i></span>
</button>
</span>
<input type="text" id="trig" name="quant[2]" class="form-control input-number" value="1" min="1" max="5" ng-model="onoctober">
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-number" data-type="plus" data-field="quant[2]">
<span><i class="fas fa-plus"></i></span>
</button>
</span>
</div>
</td>
</tr>
</tbody>
</table>
<input type="button" value="submit" class="btn btn-primary" ng-click="insertEval()" />
</form>
</div>
</div>
</div>
<!-- October Evaluation End -->
<br><br>
The AngularJS Controller js file:
var app = angular.module("myApp", []);
app.controller('userEval', function ($scope, $http) {
$scope.insertEval = function () {
$http.post(
"inserteval.php",
{
'gid': $scope.gid,
'onoctober': $scope.onoctober,
}).success(function (data) {
alert(data);
});
}
});
The inserteval.php file:
<?php
$connection = mysqli_connect("localhost","root","","users");
$data = json_decode(file_get_contents("php://input"));
if(count($data)>0)
{
$gid = mysqli_real_escape_string($connection,$data->gid);
$onoctober = mysqli_real_escape_string($connection,$data->onoctober);
$query = "INSERT INTO `myusers`(`name`, `on-october`) VALUES ('$gid','$onoctober')";
if(mysqli_query($connection,$query)){
echo "Done , new User added !";
}else {
echo "Error add !";
}
}
?>
Photos to illustrate:
In support of #Sujay Subrahmanya, you have to inform your html file that it is part of which app and which controller. Here is the syntax to inform it
<body ng-app="myApp" ng-controller="userEval">
<!-- Put your index.php content -->
</body>

How to update the values in input type text of the current row of main table getting the values from modal window table

I have one table with rows of input type text and one button on each row to open modal window.
I am adding the rows in the main table with the help of add row button.
In modal window I have another table with rows of data and one radio button.
I want to get the values of columns of selected row with the help of radio button. I am getting the selected row values but the values are fetched always on first row of main table.
I want to get the selected values in the current row of main table I mean the row from where I opened the modal window.
Following is the HTML code of my table........
<div class="row pt-3">
<div class="table-responsive col-md-10">
<table id="tarifftable" class="table table-sm table-bordered table-hover">
<thead class="thead-light">
<tr>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"TARIFFS","TDID"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"TARIFFS","TDSCCODE"); ?></th>
<th></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"TARIFFS","SCDESC"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"TARIFFS","TDRATE"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"TARIFFS","TDREMARKS"); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="text-control input-sm" readonly name="tdid[]" id="tdid"
value="1" style="text-align:right;width:50px;" maxlength="4" />
</td>
<td>
<input type="text" class="text-control" name="tdsccode[]" id="tdsccode"
style="width:100px;" maxlength="50" />
</td>
<td>
<a href="#" data-toggle="modal" data-target="#serviceModal" class="btn btn-info btn-xs">
<i class="fa fa-search"></i>
</a>
</td>
<td>
<input type="text" class="text-control" name="tdscdesc[]" id="tdscdesc" readonly
style="width:200px;" maxlength="250" />
</td>
<td>
<input type="number" class="text-control" name="tdrate[]" id="tdrate"
style="text-align:right;width:90px" maxlength="17" />
</td>
<td>
<input type="text" class="text-control" name="tdremarks[]" id="tdremarks"
style="width:200px" maxlength="100" />
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-2 pl-0">
<button type="button" name="addrow" id="addrow" class="btn btn-success fa fa-plus btn-sm"></button>
</div>
</div>
Following is the JavaScript code for adding new row....
<script>
$(document).ready(function(){
var allInputs = document.querySelectorAll('table tr input[name="tdid[]"]');
var rowcount = allInputs[allInputs.length - 1].value;
var count=parseInt(rowcount);
$(document).on('click','#addrow', function(){
count=count+1;
var html_code='';
html_code +='<tr id="row_id_'+count+'">';
html_code += '<td><input type="text" class="text-control input-sm" name="tdid[]" id="tdid" readonly style="text-align:right;width:50px" value="'+count+'"/></td>';
html_code +='<td><input type="text" class="text-control" name="tdsccode[]" id="tdsccode" style="width:100px;" maxlength="50" /> </td>';
html_code +='<td><i class="fa fa-search"></i></td>';
html_code +='<td><input type="text" class="text-control" name="tdscdesc[]" id="tdscdesc" readonly style="width:200px;" maxlength="250" /></td>'
html_code +='<td><input type="number" class="text-control" name="tdrate[]" id="tdrate" style="text-align:right;width:90px" maxlength="17" /></td>'
html_code +='<td><input type="text" class="text-control" name="tdremarks[]" id="tdremarks" style="width:200px" maxlength="100" /></td>';
//html_code +='<td><button type="button" name="removerow" id="removerow" class="btn btn-danger fa fa-remove"></button></td>';
html_code +='</tr>';
$('#tarifftable').append(html_code);
//alert(count);
//}
});
});
</script>
Following is the HTML code for modal window......
<div id="serviceModal" class="modal show fade" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title"><?php echo GetBilingualLabels($_SESSION['$language'],"VATSETUP","SERVICELIST");?></h6>
</div>
<div class="modal-body">
<div class="control-container" style="padding:10px;">
<div class="row pt-1">
<div class="col-md-3">
<label><?php echo GetBilingualLabels($_SESSION['$language'],"SEARCHTABLE","SEARCHBY"); ?></label>
</div>
<div class="col-md-3">
<select id="searchby" class="text-control">
<option value="1"><?php echo GetBilingualLabels($_SESSION['$language'],"SERVICECODE","SCCODE"); ?></option>
<option value="2"><?php echo GetBilingualLabels($_SESSION['$language'],"SERVICECODE","SCDESC"); ?></option>
</select>
</div>
<div class="col-md-6">
<input type="text" id="searchvalue" class="text-control" onkeyup="FilterFunction('serviceTable','searchby','searchvalue')" style="width:100%"
placeholder="<?php echo GetBilingualLabels($_SESSION['$language'],"SEARCHTABLE","SEARCHVALUE"); ?>" />
</div>
</div>
<div class="line"></div>
<table id="serviceTable" class="table table-sm table-bordered table-hover table-lightfont paginated">
<thead class="thead-light">
<tr>
<th></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"SERVICECODE","SCCODE"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"SERVICECODE","SCDESC"); ?></th>
</tr>
</thead>
<tbody>
<?php
if ($_SESSION['$language']=="E") {
$servicedata=SelectData("service_code","sc_code,sc_desc","","sc_code");
}
else {
$servicedata=SelectData("service_code","sc_code,sc_bldesc as sc_desc","","sc_code");
}
$rownum=0;
foreach ($servicedata as $servicedata) {
echo "<tr id=$rownum>
<td><input type='radio' name='serviceradio' id='serviceradio' value='{$servicedata['sc_code']}'></td>
<td>{$servicedata['sc_code']}</td>
<td>{$servicedata['sc_desc']}</td>
</tr>";
$rownum+=1;
} ?>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">
<i class="fa fa-close"></i>
<?php echo GetBilingualLabels($_SESSION['$language'],"BUTTON","CANCEL"); ?>
</button>
<button type="button" name="selectservice" id="selectservice" class="btn btn-success"> <!--onclick="DispMsg(<//?php echo "'".$_SESSION['AlertMsg']."'";?>)"-->
<i class="fa fa-check"></i>
<?php echo GetBilingualLabels($_SESSION['$language'],"BUTTON","SELECTLIST"); ?>
</button>
</div>
</div>
</div>
</div>
Following is the JavaScript for getting the selected values from modal window into main table.....
<script>
$(document).ready(function(){
$(document).on('click','#selectservice',function(){
var service = document.getElementsByName('serviceradio');
var scdesc = document.getElementsByName('scdesc');
for(i = 0; i < service.length; i++) {
if(service[i].checked) {
var Row = document.getElementById(i);
var Cells = Row.getElementsByTagName("td");
document.getElementById('tdsccode').value= service[i].value;
document.getElementById('tdscdesc').value=Cells[2].innerText;
}
}
$('#serviceModal').modal('hide');
});
</script>
Thanks everybody for the support but i have solved the issue by myself as follows..
1)i have set the id of my main table input text with count value.
2)on the button to show the modal window i have set the data-book-id with the value of count.
2)i have created one input type text with display none attribute
3)on modal show event i have set the value of this input type text with passed data-book-id value
4)then i concatenated this value with the id of the input type text in main table.
This way i am getting the value set of the current row of input type text.

Am creating a dynamic input field survey App

I am creating a survey app that dynamically adds a dropdown box , and two text boxes.Once an option is selected from the dropdown it populates the selected option . Unforunately the first option works but for the others it simply populates the data I selected in the first.The overall goal is to input it inside a database using php.This is my php script
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
$number = count($_POST["name"]);
$crops = count($_POST["selectedCrop"]);
// echo $number;
// echo $crop;
if ($number > 0) {
for ($i=0; $i<$number; $i++) {
if (trim($_POST["name"][$i] != '')) {
$sql = "INSERT INTO tbl_name(name,crop) VALUES('".mysqli_real_escape_string($connect, $_POST["selectedCrop"][$i])."' ,'".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";
mysqli_query($connect, $sql);
}
}
echo "Data Inserted";
} else {
echo "Please Enter Name";
}
The result are as follows The Image with the duplicated resukts
Here is my HTML Code and the Javascript I am using to achieve
<body>
<div class="container">
<div class="page-header">
<h1 class="text-center">SURVEY</h1>
</div>
<div class="container">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<strong>E. FARMING AND AGRIBUSINESS </br>Farming</strong>
</div>
<div class="panel-body">
Which of the value chains did your household produce in September 2016 through rain fed production mechanisms? Or you produce now through rain fed production mechanisms?<i>Select all options applicable – 1, 2 up to last</i>
<br />
<form name="add_name" id="add_name">
<!-- This is the Table That I am adding the widgets dynamically -->
<table class="table table-striped table-bordered" id="dynamic_field">
<thead>
<tr>
<th>Name of Crop Options</th>
<th>Crop Selected</th>
<th>Produced/produce this value chain in 2015/2016?</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="dropdown" name= "crops[]">
<button id="crop" onchange="copyValue()" class="btn dropdown-toggle" type="button" data-toggle="dropdown" >
Name of Crop<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Maize</li>
<li>Beans</li>
<li>Tomatoes</li>
<li>Potatoes</li>
</ul>
</div>
</td>
<td>
<input type="text" name="selectedCrop[]" id="selectedCrop" placeholder="Enter your Name" class="form-control name_list" />
</td>
<td>
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
</td>
<td>
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
</td>
<!-- <td><button type="button" name="remove" id="'0'" class="btn btn-danger btn_remove">X</button></td></tr> -->
</tr>
</tbody>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><div class="dropdown" name= "crops[]"><button class="btn dropdown-toggle" type="button" data-toggle="dropdown" >Name of Crop<span class="caret"></span></button><ul class="dropdown-menu"><li>Maize</li> <li>Beans</li><li>Tomatoes</li><li>Potatoes</li></ul></div></td><td><input type="text" name="selectedCrop[]" id="selectedCrop" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"farming_and_agribusiness_1_copy.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
$(function(){
$(".dropdown-menu li a").click(function(){
$("#crop:first-child").text($(this).text());
$("#crop:first-child").val($(this).text());
$("#selectedCrop:first-child").text($(this).text());
$("#selectedCrop:first-child").val($(this).text());
});
});
</script>
<!-- Survey - END -->
</div>
</body>

Get data-price attribute from dynamically added row and put inside the input box

how to get data-price inside the text box using select in php html and sql?
i tried this so far. what im trying to do is, when i change the selection box, the input box beside should change base on the value of data-price.
been trying this for a week.
e.g
select debit
local treasury 100
<script>
$(document).ready(function(){
var i=1;
var chart_add = '<tr id="row_chart'+i+'"><td><select name="chart_of_account[]" class="selectpicker" data-live-search="true"><option style="width: 400px;">--Select Chart of Account--</option><?php $chart=mysqli_query($conn,"Select acoount_no,account_title from chart_of_account"); while($row=mysqli_fetch_assoc($chart)){$account_no = $row["acoount_no"]; $account_title = $row["account_title"];?><option value="<?php echo $account_no; ?>" style="width: 400px;"><?php echo $account_no ." | ". $account_title; ?></option><?php }?></select></td><td><input type="text" name="chart_debit[]" class="form-control chart_debit" id="chart_debit"onchange="chart_change_debit()"></td><td><input type="text" name="chart_credit[]" class="form-control chart_credit" id="chart_credit" onchange="chart_change_credit()"></td><td><button type="button" name="remove_chart" id="'+i+'" class="btn btn-danger remove_chart">X</button></td></tr>';
$('#add').click(function(){
i++;
$('#dynamic_field').append(chart_add);
$('.selectpicker').selectpicker('render');
$('.chart_debit').val($('select[name="chart_of_account"] option:selected').data('price'));
});
$(document).on('click', '.remove_chart', function(){
var button_id = $(this).attr("id");
$('#row_chart'+button_id+'').remove();
});
});
</script>
<form method = "POST" name="add_name" id="add_name">
<div class="row">
<div class="col-md-12">
<!-- chart of account -->
<div class="row">
<div class="col-md-12">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Chart of Account</h3>
</div>
<div class="box-body">
<table class="table table-bordered" id="dynamic_field">
<tr>
<th rowspan="2">Chart of Account</th>
<th>Debit</th>
<th>Credit</th>
<th rowspan="2"><button type="button" name="add" id="add" class="btn btn-success">Add More</button></th>
</tr>
<tr>
<th>
<input type="text" name="chart_debit_sum" class="form-control chart_debit_sum" id="chart_debit_sum" readonly>
</th>
<th>
<input type="text" name="chart_credit_sum" class="form-control chart_credit_sum" id="chart_credit_sum" readonly>
</th>
</tr>
<tr>
<td>
<select name="chart_of_account[]" class="selectpicker" data-live-search="true">
<option style="width: 400px;">--Select Chart of Account--</option>
<?php
$chart = mysqli_query($conn,"Select acoount_no,account_title from chart_of_account");
while($row = mysqli_fetch_assoc($chart)){
$account_no = $row['acoount_no'];
$account_title = $row['account_title'];
$amount = $row['test_amount'];
?>
<option value = "<?php echo $account_no; ?>" style="width: 400px;" data-price = "<?php echo $amount; ?>">
<?php echo $account_no . " | " .$account_title; ?>
</option>
<?php } ?>
</select>
</td>
<td>
<input type="text" name="chart_debit[]" class="form-control chart_debit" id="chart_debit" onchange="chart_change_debit()">
</td>
<td>
<input type="text" name="chart_credit[]" class="form-control chart_credit" id="chart_credit" onchange="chart_change_credit()">
</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- chart of account -->
</div>
<!-- chart and sub-->
</div>
</form>
sample screenshot

Form is presenting same data in php while loop

I am trying to get an edit form to work with the loop in the php. I have a delete button and it works just fine. The edit form keeps presenting only the first row in the table. In firebug, it shows that all the other forms are there with the correct unique id for each but only the first form shows when edit is clicked on different rows. Can someone help me as to why?
<table id="table_id" class="table table-hover table-striped">
<thead>
<tr>
<th>ID #</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($search_sql)) {
?>
<tr>
<td id = "clicked"><?=$row['ID']?></td>
<td id = "clicked"><?=$row['Product']?></td>
<td id = "clicked"><?=$row['Quantity']?></td>
<td id = "clicked">$ <?=$row['Price']?></td>
<td>
<button class="btn btn-warning btn-sm" onclick="div_show2(this, '<?=$row['ID']?>'); return false;"><span class="glyphicon glyphicon-edit"></span>Edit</button>
<!-- Modal for the Edit Data Form -->
<div id ="hidden-form2">
<div id = "popupContact">
<form action= "updateData.php" id = "editForm<?=$row['ID']?>" method="POST" name="editForm">
<input type="hidden" name="ID" value="<?=$row['ID']?>">
<div class="form-group">
<label for="product">Product</label>
<input type="text" class="form-control" id="product<?=$row['ID']?>" name="product" value="<?=$row['Product']?>">
</div>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="text" class="form-control" id="quantity<?=$row['ID']?>" name="quantity" value="<?=$row['Quantity']?>">
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price<?=$row['ID']?>" name="price" value="<?=$row['Price']?>">
</div>
<button type="button" class="btn btn-default" onclick="formHide2()">Close</button>
<button type="submit" id="save" class="btn btn-primary">Save changes</button>
</form>
</div>
</div>
<!--End of Edit Form-->
</td>
<td>
<!--Delete Button Form-->
<form method="post" action="deleteData.php">
<button class="btn btn-danger btn-sm" type="submit"><span class="glyphicon glyphicon-trash"></span>Delete</button>
<input type="hidden" id="ID" name="ID" value="<?=$row['ID']?>">
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
//script for calling the edit forms as a modal popup
//Function To Display Popup for Edit form
function div_show2() {
document.getElementById("editForm").reset();
document.getElementById('hidden-form2').style.display = "block";
}
//Function to Hide Popup
function formHide2(){
document.getElementById('hidden-form2').style.display = "none";
}
Your show_div2 function is only showing one element.
document.getElementById('hidden-form2').style.display = "block";
That shows you why you are only seeing the first row.
Update your HTML and Javascript as follows
HTML
<div id="hidden-form2<?=$row['ID']?>">
Javascript
function div_show2(id) {
document.getElementById("editForm"+id).reset();
document.getElementById('hidden-form2'+id).style.display = "block";
}
To avoid having any problems like this in the future, always make sure that your id's are unique.
The first 4 td I see all use the same id name clicked. Try to fix that first and see what happens.
<td class="clicked" id="clickedID<?=$row['ID']?>"><?=$row['ID']?></td>
<td class="clicked" id="clickedProduct<?=$row['ID']?>"><?=$row['Product']?></td>
<td class="clicked" id="clickedQuantity<?=$row['ID']?>"><?=$row['Quantity']?></td>
<td class="clicked" id="clickedPrice<?=$row['ID']?>">$ <?=$row['Price']?></td>

Categories