Am creating a dynamic input field survey App - javascript

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>

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.

Enable Edit button if new record exists

I created a modal where I can insert new client record and edit the same record. But in relation to the edit button, I wanted it to be active only when there was a new record in the database and until the end of the day it was registered.
<a type="button" name="editar" id="'.$row["IdCliente"].'" data-toggle="modal" href="#add_data_Modal" class="btn btn-primary edit_data">Update</a>
I'm trying this way:
if(isset($_POST["employee_id3"]))
{
$output = '';
$query = "SELECT * FROM centrodb.PsicUtentes LEFT OUTER JOIN centrodb.PsicUtentesConsulta ON centrodb.PsicUtentesConsulta.CodigoUtente2 = centrodb.PsicUtentes.CodigoUtente WHERE centrodb.PsicUtentes.Id = '".$_POST["employee_id3"]."' ORDER BY IdConsulta DESC ";
$result = mysqli_query($conn, $query);
$output;
while($row = mysqli_fetch_array($result))
{
$dataAtual = DATE('Y-m-d');
$disabled = "";
if(DATE($row['Data2'])!=$dataAtual){
$disabled = "disabled";
}
$output .= '
<h4 class="modal-title">Histórico de Consultas</h4>
<div>
<button type="button" class="exibir botao" href="#" aria-hidden="true">+</button>
<button type="button" href="#" class="ocultar botao" aria-hidden="true">-</button>
</div>
<div class="conteudo">
<form method="post" id="insert_form6">
<div style="float:right">
<a type="button" name="edit3" id="'.$row["Id"].','.$row["IdConsulta"].'" data-toggle="modal" href="#add_data_Modal3" class="btn btn-primary edit_data3" "$disabled">Editar</a>
</div>
<br/>
<br/>
<br/>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<input type="Hidden" id="IdConsulta1" name="IdConsulta" class="form-control" value="'.$row["IdConsulta"].'" style="width:150px;" readonly="true" />
</td>
<td>
<label>Data Consulta</label>
<input type="text" id="Data23" name="Data2" class="form-control" value="'.$row["Data2"].'" style="width:150px;" readonly="true" />
</td>
<td>
<label>Código Utente</label>
<input type="number" id="CodigoUtente5" name="CodigoUtente" value="'.$row["CodigoUtente"].'" class="form-control" style="width:100px;" readonly="true"/>
</td>
<td>
<label>Nome Utente</label>
<input type="text" id="Nome5" name="Nome" value="'.$row["Nome"].'" class="form-control" style="width:400px;" readonly="true"/>
</td>
<td>
<label>Data Nascimento</label>
<input type="date" id="DataNasc5" name="DataNasc" value="'.$row["DataNasc"].'" class="form-control" style="width:150px;" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>Data Admissao</label>
<input type="date" id="DataAdmissao5" name="DataAdmissao" value="'.$row["DataAdmissao"].'" class="form-control" style="width:150px;" readonly="true"/>
</td>
<td>
<label>Valência</label>
<input type="text" id="ValenciasDescricao5" name="ValenciasDescricao" value="'.$row["ValenciasDescricao"].'" class="form-control" style="width:200px;" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>Observação</label>
</p><textarea rows="6" cols="130" readonly="true">'.$row["Descricao"].'</textarea>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>O Psicologo/a</label>
<input type="text" id="Colaborador2" name="Colaborador2" class="form-control" style="width:150px;" value="'.$row["Colaborador2"].'" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
</form>
</div>
';
}
$output;
echo $output;
}
<script>
$(document).ready(function(){
$(document).on('click', '.edit_data3', function(){
var employee_id3 = $(this).attr("Id");
$.ajax({
url:"./fetch2",
method:"POST",
data:{employee_id3:employee_id3},
dataType:"json",
success:function(data){
$('#IdConsulta').val(data.IdConsulta);
$('#Data22').val(data.Data2);
$('#CodigoUtente6').val(data.CodigoUtente2);
$('#Descricao1').val(data.Descricao);
$('#Colaborador2').val(data.Colaborador2);
$('#employee_id3').val(data.Id);
$('#insert3').val("Gravar");
$('#add_data_Modal3').modal('show');
}
});
});
$('#insert_form7').on("submit", function(event){
event.preventDefault();
if($('#CodigoUtente6').val() == "")
{
alert("Código Utente é necessário");
}
else if($('#Descricao1').val() == "")
{
alert("Observação é necessária");
}
else
{
$.ajax({
url:".conexao9",
method:"POST",
data:$('#insert_form7').serialize()
,
beforeSend:function(){
$('#insert3').val("Inserting");
},
success:function(data){
$('#insert_form7')[0].reset();
$('#add_data_Modal3').modal('hide');
$('#employee_table').html(data);
location.reload("add_data_Modal3");
}
});
}
});
});
</script>
I created a variable with the current date that compares with the date of the record. I created an empty disabled variable. There I put this disabled variable in the link. If the date is different than the current date you put the disabled variable filled.The problem is that the button stays in the same asset.
Firstly your code is vulnerable to sql injection attacks and you should use prepared statements.
Then you have some syntax errors on your code.
The lines $output; are useless, delete them.
Change "$disabled" to '.$disabled'.
and put ?> before your <script> tag.

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

Ajax not working on multiple inserts - CI

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">

Categories