Laravel, javascript add rows table class select not working - javascript

I have this code which works fine. my problem is that when i go to add one or more rows in the table with the button
the select:
<select name = "product_id_product []" id = "product_id_product '. $ request-> count_product.'" class = "form-control js-select2" required>
it is as if it does not take the "js-select2" class
if instead I insert it manually in the index bypassing the whole class it works
I just can't figure out how to do it ..
index.blade:
<div class="card-body" style="text-align: center;">
<button type="button" name="aggiungi_prodotto" id="aggiungi_prodotto" class="btn btn-primary aggiungi_prodotto" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Prodotto</button>
<button type="button" name="aggiungi_accessorio" id="aggiungi_accessorio" class="btn btn-success aggiungi_accessorio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Accessorio</button>
<button type="button" name="aggiungi_servizio" id="aggiungi_servizio" class="btn btn-warning aggiungi_servizio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Servizio</button>
<button type="button" name="aggiungi_riga" id="aggiungi_riga" class="btn btn-danger aggiungi_riga" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Riga</button> <br/><br/><br/>
<div class="form-row">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th width="50%">Prodotto</th>
<th width="10%">Quantità</th>
<th width="10%">Acconto</th>
<th width="10%">Costo</th>
<th width="10%">Sconto TOT</th>
<th width="10%">Azioni</th>
</tr>
</thead>
<tbody id="prodottiRows">
</tbody>
</table>
</div>
</div>
<hr>
</div>
Javascript:
var count_prodotto = 0;
$(document).on('click', '#aggiungi_prodotto', function(){
count_prodotto = count_prodotto + 1;
var categorieID = document.getElementById('categorie_id').value;
var brandID = document.getElementById('brand_id').value;
var modelloID = document.getElementById('modello_id').value;
$.ajax({
type: 'POST',
url: "{{ route('autocomplete.fetch_prodotti') }}",
data: {
'_token': $('input[name=csrf-token]').val(),
'categorie_id':categorieID,
'brand_id':brandID,
'modello_id':modelloID,
'count_prodotto':count_prodotto
},
success:function(data){
$('#prodottiRows').append(data);
}
});
});
Controller:
public function fetch_prodotti(Request $request)
{
$products = Product::with('Multitenantable')
->where("stato_prodotto",'1')
->where("categorie_id",$request->categorie_id)
->where("brand_id",$request->brand_id)
->where("modello_id",$request->modello_id)
->pluck("nome_prodotto","id");
$prodotti = '
<tr id="row_prodotto'.$request->count_prodotto.'">
<td><select name="product_id_prodotto[]" id="product_id_prodotto'.$request->count_prodotto.'" class="form-control js-select2" required>
<option value="">Seleziona Prodotto</option>';
foreach ($products as $key => $product) {
$prodotti .= '<option value="'.$key.'">'.$product.'</option>';
# code...
}
$prodotti .='</select></td>
<td><input type="text" name="quantita_prodotto[]" id="quantita_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="acconto_prodotto[]" id="acconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="costo_prodotto[]" id="costo_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="sconto_prodotto[]" id="sconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td data-column="Rimuovi"><button type="button" name="remove_prodotto" id="'.$request->count_prodotto.'" class="btn btn-danger btn-xs remove_prodotto">Rimuovi</button></td>
</tr>';
return response()->json($prodotti);
}

Related

OnChange Not Working in cloned Input fields

I have created a form and in the form I have given room to clone input fields ie add or delete rows.
In one input field I am using Jquery Ajax to get the value.
Unfortunately after adding an additional role ie cloning the parent row to get a child row, ajax does not pass the value for the input field expecting it value from the Ajax.
I have attached the code below to explain better
function restrictAlphabets(e) {
var x = e.which || e.keyCode;
if ((x >= 48 && x <= 57))
return true;
else
return false;
}
// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
let tbody = e.target.closest('table').querySelector('tbody');
let clone = tbody.firstElementChild.cloneNode(true);
clone.querySelector('button[data-name="del"]').hidden = false;
clone.querySelectorAll('input, select').forEach(n => {
n.value = '';
});
tbody.appendChild(clone);
});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
e.stopPropagation();
if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
let tbody = e.target.closest('table').querySelector('tbody');
if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
}
});
// Below begins AJAX Function
function checkDeviceStatus() {
var dModel = $("#model").val();
var dBrand = $("#brand").val();
var dserial = $("#serialNo").val();
var client = $("#client").val();
$.ajax({
url: "./handlers/slaChecker.php",
type: "POST",
data: {
dModel: dModel,
dserial: dserial,
client: client,
dBrand: dBrand,
},
success: function(result) {
$("#deviceLevel").val(result);
console.log(result);
}
})
}
<div class="col-xl-8 col-md-12">
<form>
<div class="card">
<div class="card-header">
<h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Reps Name<span class="text-red">*</span></label>
<input type="text" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">E-Mail<span class="text-red">*</span></label>
<input type="email" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Phone No.<span class="text-red">*</span></label>
<input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
<input type="date" name="" value="<?=date(" Y-m-d ")?>" hidden="">
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
</div>
<div class="card-body">
<?php
if ($clientType === $slaClient) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th class="text-center">Device Brand</th>
<th class="text-center">Device Model</th>
<th class="text-center">Serial Number</th>
<th class="text-center" style="width:10%">SLA Device</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="brand[]" required="" id="brand" onchange="checkDeviceStatus()">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model" onchange="checkDeviceStatus()">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control" id="serialNo" onchange="checkDeviceStatus()"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
<!-- End of Input field -->
</td>
<input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
if ($clientType === $nonSla) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th>Product Model Non-SLA</th>
<th>Serial Number Non-SLA</th>
<th>Device Status Non-SLA</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</div>
</form>
</div>
The main problem is that when you clone, you will get duplicated id's. An Id must always be unique.
I would suggest that you change the ID to class or something else and do something like this.
function checkDeviceStatus(obj) {
var dModel = $(obj).closest("tr").find(".model").val();
var dBrand = $(obj).closest("tr").find(".brand").val();
var dserial = $(obj).closest("tr").find(".serialNo").val();
var client = $(obj).closest("tr").find(".client").val();
console.log("dserial:"+dserial);
//Removed ajax for demo.
}
And then add this to your onchange="checkDeviceStatus()" like onchange="checkDeviceStatus(this)"
Demo
function restrictAlphabets(e) {
var x = e.which || e.keyCode;
if ((x >= 48 && x <= 57))
return true;
else
return false;
}
// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
let tbody = e.target.closest('table').querySelector('tbody');
let clone = tbody.firstElementChild.cloneNode(true);
clone.querySelector('button[data-name="del"]').hidden = false;
clone.querySelectorAll('input, select').forEach(n => {
n.value = '';
});
tbody.appendChild(clone);
});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
e.stopPropagation();
if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
let tbody = e.target.closest('table').querySelector('tbody');
if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
}
});
// Below begins AJAX Function
function checkDeviceStatus(obj) {
var dModel = $(obj).closest("tr").find(".model").val();
var dBrand = $(obj).closest("tr").find(".brand").val();
var dserial = $(obj).closest("tr").find(".serialNo").val();
var client = $(obj).closest("tr").find(".client").val();
console.log("dserial:"+dserial);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-xl-8 col-md-12">
<form>
<div class="card">
<div class="card-header">
<h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Reps Name<span class="text-red">*</span></label>
<input type="text" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">E-Mail<span class="text-red">*</span></label>
<input type="email" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Phone No.<span class="text-red">*</span></label>
<input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
<input type="date" name="" value="<?=date(' Y-m-d ')?>" hidden="">
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
</div>
<div class="card-body">
<?php
if ($clientType === $slaClient) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th class="text-center">Device Brand</th>
<th class="text-center">Device Model</th>
<th class="text-center">Serial Number</th>
<th class="text-center" style="width:10%">SLA Device</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;">ADD</i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td>
<select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="" onchange="checkDeviceStatus(this)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="" onchange="checkDeviceStatus(this)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control serialNo" onchange="checkDeviceStatus(this)"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
<!-- End of Input field -->
</td>
<input type="text" name="" class="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
if ($clientType === $nonSla) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th>Product Model Non-SLA</th>
<th>Serial Number Non-SLA</th>
<th>Device Status Non-SLA</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</div>
</form>
</div>
I have found solution to it.
The classes as you all suggested wasn't Ideal instead this is what I did.
the ids has to be unique so I created a variable for it to be handling the additional ids.
This worked perfectly for me.
Php is now working fine and Ajax is also working fine.
$(document).ready(function() {
var num = 1;
var c = `
<tr id="row_num" >
<td>
<select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="brand_num" onchange="checkDeviceStatus(_num)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>"><?=$brandName?></option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="model_num" onchange="checkDeviceStatus(_num)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>"><?=$modelName?></option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control serialNo" id="serialNo_num" onkeyup="checkDeviceStatus(_num)"></td>
<!-- The input field below is to get value from AJAX -->
<td>
<input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel_num">
<!-- End of Input field -->
</td>
<td><button type="button" onclick="DeleteRow(_num)" class=" btn text-danger remove" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
`;
$(".addRow").click(function(e) {
var cc = c;
// e.preventDefault();
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
$(".table_body").append(cc);
num++;
console.log(num);
});
});
<tbody class="field_wrapper showRow table_body" id="table_body">
<tr id="row0">
<td>
<select class="form-control form-select" data-bs-placeholder="Select" name="brand[]" required="" id="brand0" onchange="checkDeviceStatus(0)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model0" onchange="checkDeviceStatus(0)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control " id="serialNo0" onkeyup="checkDeviceStatus(0)"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel0">
<!-- End of Input field -->
</td>
<input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-success addRow" data-name='add'><i class="fe fe-plus-circle " data-id='ad' style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>

Column cannot be null by using Auth

I'm inserting multiple data into the database. There is an error for my column report_by which is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'report_by' cannot be null (SQL: insert into 'complaints' ('defect_id', 'image', 'description', 'report_by') values (1, C:\wamp64\tmp\php8E2E.tmp, leak, ?)) Inside column report_by should be the id of the user by using Auth. It's to tell that the complaint made by which users.
users table
id
role
email
typable_id
typable_type
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Complaint;
use Illuminate\Http\Request;
class ComplaintController extends Controller
{
public function index()
{
return view('buyers.complaint');
}
public function create(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $request->image[$item],
'description' => $request->description[$item],
'report_by' => $request->user_id,
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
}
complaint.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>Make New Report</strong></h3>
</div>
<div class="panel-body">
<div>
<div class="panel">
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</form>
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
Here my javascript inside the blade
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += ' <td><input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}"><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += ' <td><input type="file" class="form-control-file" name="image[]"></td>';
html += ' <td><input type="text" class="form-control" name="description[]"></td>';
html += ' <td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop

Getting the values from dynamicly created input(s) from a table

I have a table
<form id="project-form">
<table id="project-table" class="table table-striped table-inverse table-responsive">
<caption>Projects</caption>
<thead class="thead-inverse">
<tr>
<th scope="col">#</th>
<th scope="col">Project name</th>
<th scope="col">Description</th>
<th scope="col">Estimated time (min)</th>
<th scope="col">Actual time (min)</th>
<th scope="col">Add task</th>
<th scope="col">Delete project</th>
</tr>
</thead>
<tbody id="project-body">
</tbody>
</table>
</form>
This table is filled with data from an AJAX GET request
function getProjects() {
$.ajax({
method: 'GET',
dataType: 'json',
data: {
functionToCall: 'project',
},
url: 'http://localhost/WBS/php/api/requests/get.php',
success: (response) => {
$.each(response, function () {
$.each(this, function (index, value) {
$('#project-body').append(
`
<tr>
<td>
<input class="form-control" type="hidden" name="projectid" id="projectid" value="${value.projectid}">
</td>
<td>
<input class="form-control" type="text" name="projectName" id="projectName" value="${value.title}">
</td>
<td>
<input class="form-control" type="text" name="description" id="description" value="${value.description}">
</td>
<td>
<input class="form-control" type="text" name="estimatedTime" id="estimatedTime" value="${value.Estimated_time}">
</td>
<td>
<input class="form-control" type="text" name="actualTime" id="actualTime" value="${value.Actual_time}">
</td>
<td>
<a id="addTask" class="btn btn-info" href="Overview.html?id=${value.projectid}" role="button">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Add task
</a>
</td>
<td>
<button type="button" id="deleteProject" name="deleteProject" class="btn btn-danger">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
</button>
</td>
</tr>
`
);
});
});
},
error: () => {
console.error('Something went wrong with the getProjects function');
},
});
}
There is also the option to dynamically add a new row of inputs to the table
function addProject() {
event.preventDefault();
$('#project-body').append(
`
<tr>
<td>
<input class="form-control" type="hidden" name="projectid" id="projectid" >
</td>
<td>
<input class="form-control" type="text" name="projectName" id="projectName">
</td>
<td>
<input class="form-control" type="text" name="description" id="description">
</td>
<td>
<input class="form-control" type="text" name="estimatedTime" id="estimatedTime">
</td>
<td>
<input class="form-control" type="text" name="actualTime" id="actualTime">
</td>
<td>
<a id="addTask" class="btn btn-info" href="Overview.php" role="button">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Add task
</a>
</td>
<td>
<button type="button" id="deleteProject" name="deleteProject" class="btn btn-danger">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
</button>
</td>
</tr>
`
);
}
I submit all of my data on this button
<button id="saveProjects" form="project-form" class="btn btn-info" type="button"><i class="fa fa-angle-right" aria-hidden="true"></i> Save changes</button>
In the document ready I handle all of my onclick events
$(document).ready(() => {
$('#saveProjects').on('click', () => {
uploadProjects();
});
$('#addProject').on('click', () => {
addProject();
});
});
On my PHP side I have a class that handles all of my POST requests, inside of this class is a function that will handle the uploading of new projects
public function uploadProject()
{
try {
$title = $_POST["projectName"];
$description = $_POST["description"];
$estimatedTime = $_POST["estimatedTime"];
$actualTime = $_POST["actualTime"];
$stm = $this->pdo->getCon();
$PDOStatement = $stm->prepare("INSERT INTO projects (title,description,Estimated_time,Actual_time) VALUES(:title,:description,:Estimated_time,:Actual_time)");
$PDOStatement->bindParam(':title', $title, PDO::PARAM_STR);
$PDOStatement->bindParam(':description', $description, PDO::PARAM_STR);
$PDOStatement->bindParam(':Estimated_time', $estimatedTime, PDO::PARAM_STR);
$PDOStatement->bindParam(':Actual_time', $actualTime, PDO::PARAM_STR);
$PDOStatement->execute();
header('HTTP/1.1 200 OK');
} catch (Exception $th) {
header("HTTP/1.0 404 Not Found");
throw $th->getMessage();
}
}
Now debugging my PHP code, and all the data I receive in the POST array will always correspond to the first row in the table, for example:
Let's say i have a existing row inside of my table with the values of : Project name = Hello | Description = World.
I click on the add project button and a new row is added to the table, I fill in the inputs inside of the row with something like this : Project name = Second table row | Description = Second description.
At the back-end I will always receive the values of Hello and World and not the values of the newest added row inside of the table.
I googled around a bit and only saw examples on how to the value of a SINGLE dynamically added input and not a new row.
I think you can rename your inputs like:
name="projectid[]"
Then PHP will receive an array of those values:
$total = count($_POST["projectid"]);
for ($i = 0; $i < $total; $i++) {
$title = $_POST["projectName"][$i];
$description = $_POST["description"][$i];
$estimatedTime = $_POST["estimatedTime"][$i];
$actualTime = $_POST["actualTime"][$i];
// Your INSERT query is performed here
}

Javascript, pass values to new added table row/cell

basically the objective of this request is to have a modal table that adds new table row/cells and pass the value of "var OBGyneID = $(this).attr("id"); " to first cell and value of "var billing_id = newID;" to second cell whenever new rows/cells is/are added. Seeking your help, thanks!
* MY MODAL*
<div id="myModal" class="modal fade card new-contact myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="card profile">
<div class="profile__img">
<img src="img/profile2.jpg" alt="">
</div>
<div class="profile__info">
<h3 style="text-transform:capitalize;" id="pxname" name="pxname"></h3>
<ul class="icon-list">
<li>LAST <p name="consdates" id="consdates"></p></li>
<li>Last visit: </li>
<li><i class="zmdi zmdi-twitter"></i> #mallinda-hollaway</li>
</ul>
</div>
</div>
<div>
<div class="table-responsive">
<table id="billingTable" class="table table-inverse table-sm table-hover table-condensed" style="font-size:120%">
<thead>
<th>OBDYID</th>
<th>CK</th>
<th>PROCEEDURE</th>
<th>AMOUNT</th>
</thead>
<tbody id="billing_body" style="text-transform:capitalize;">
<form method="get" id="insert_form">
<tr>
<td width="10%"><input type="text" style="width:100%;" id="OBGyneID" name="OBGyneID"></td>
<td width="10%"><input type="text" style="width:100%;" id="AssessMentEntryID" name="AssessMentEntryID"></td>
<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" id="ExamDesc" name="ExamDesc"></td>
<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" id="Price" name="Price"></td>
</tr>
</form>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
<input type="submit" id="addRow" value="add" name="add" class="btn btn-info" />
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
* MY JS to add new rows/cells*
$(document).ready(function () {
$("#addRow").click(function () {
$("#billingTable").append('<tr><td width="10%"><input type="text" style="width:100%;" id="OBGyneID" name="OBGyneID" ></td>'+
'<td width="10%"><input type="text" style="width:100%;" id="AssessMentEntryID" name="AssessMentEntryID"></td>'+
'<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" id="ExamDesc" name="ExamDesc"></td>'+
'<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" id="Price" name="Price"></td></tr>');
jQuery(".ExamDesc").autocomplete({
source: 'php/billingentry.php'
});
});
});
* Pass values to Modal * this will only pass value when modal pops-up but cant pass value whenever new rows/cells are added.
$(document).on('click', '.billing_data', function(){
var OBGyneID = $(this).attr("id");
var newID = new Date().getUTCMilliseconds();
var billing_id = newID;
$.ajax({
url:"php/billing_fetch.php",
method:"GET",
data:{OBGyneID: OBGyneID},
dataType:"json",
success:function(data){
$('#AssessMentEntryID').val(data.AssessMentEntryID);
$('#ExamDesc').val(data.ExamDesc);
$('#Price').val(data.Price);
$('#pxservice').val(data.pxservice);
$('#companyname').val(data.companyname);
$('#chiefcomplain').val(data.chiefcomplain);
document.getElementById("OBGyneID").value = OBGyneID;
document.getElementById("AssessMentEntryID").value = billing_id;
document.getElementById("pxname").innerHTML = (data.fname)+" "+(data.mi)+" "+(data.lname);
document.getElementById("consdates").innerHTML = (data.obgyneDate);
$('#myModal').modal('show');
}
});
});
whenever you are adding a new row HTML in billing table, you are using the same id for OBGyneID, AssessMentEntryID,ExamDesc and Price. And if you added two rows, DOM will not be able to work properly as there are multiple same ids out there. So I will suggest you to replace that with class and use class name to set values. Check below code:
$(document).ready(function () {
$("#addRow").click(function () {
$("#billingTable").append('<tr><td width="10%"><input type="text" style="width:100%;" class="OBGyneID" name="OBGyneID" ></td>'+
'<td width="10%"><input type="text" style="width:100%;" class="AssessMentEntryID" name="AssessMentEntryID"></td>'+
'<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" name="ExamDesc"></td>'+
'<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" name="Price"></td></tr>');
jQuery(".ExamDesc").autocomplete({
source: 'php/billingentry.php'
});
});
});
One you have added HTML code, then you can find out last row of billingTable and can set vales in that. Check below code:
$(document).on('click', '.billing_data', function(){
var OBGyneID = $(this).attr("id");
var newID = new Date().getUTCMilliseconds();
var billing_id = newID;
$.ajax({
url:"php/billing_fetch.php",
method:"GET",
data:{OBGyneID: OBGyneID},
dataType:"json",
success:function(data){
$("#billingTable").find(".AssessMentEntryID:last").val(data.AssessMentEntryID);
$("#billingTable").find(".ExamDesc:last").val(data.ExamDesc);
$("#Price").find(".Price:last").val(data.Price);
$("#billingTable").find(".consdates:last").html(data.obgyneDate);
//and so on
$('#myModal').modal('show');
}
});
});
Also, I would suggest you to use HTMl template tag for making clone for row. Appending HTML in JS is not a recommended way. Hope it helps you.

laravel mutliple row save to database

I am a laravel beginner. Currently i am learning to do an inventory system. I have two table: goodsreceiveheader and goodsreceivedetail.
What can i do to allow multiple row save into database when submit button are clicked. Hope somebody will help me out as i had stuck in this for a few weeks=(
For goodsreceiveheader table, i have the field of:
id,
referencenumber,
vendorid(FK),
date,
createdby.
While goodsreceivedetail table, i have the field of:
id,
goodsreceiveheader_id(FK),
itemid(FK),
quantity,
costprice.
create.blade.php
#extends('admin.layout')
#section('content')
<fieldset>
<legend>Create New Goods Receive</legend>
#include('layouts.error')
{!! Form::open(['url' => 'goodsreceive/save', 'method'=>'post']) !!}
#include('goodsreceiveheader.partial._goodsreceiveheader_form')
{!! Form::close() !!}
</fieldset>
#endsection
My view:
<style>
div#gr{
padding: 20px;
border:1px solid black;
}
</style>
<div class="container">
<h2>Goods Receive</h2>
<hr>
<div id="gr" class="row" style="background-color: lightgoldenrodyellow">
<div class="col-lg-4 col-sm-6">
<input name="createdby" type="hidden" value="{{ Auth::user()->name }}">
{!! Form::label('referencenumber', 'Reference Number:')!!}
<div class="form-group">
<input type="text" name="referencenumber" class="form-control" placeholder="Reference Number">
</div>
</div>
<div class="col-lg-4 col-sm-6">
{!! Form::label('date', 'Receive Date:')!!}
{!! Form::date('date',null,['class'=>'form-control']) !!}
</div>
<div class="col-lg-4 col-sm-6">
{!! Form::label('vendorid', 'Vendor ID:')!!}
<select name="vendorid" class="form-control">
<option value="" selected disabled>Please Select Vendor..</option>
#foreach($vendors as $vendor)
<option value="{{$vendor->id}}">{{$vendor->vendorid}}</option>
#endforeach
</select>
</div>
</div>
<br>
<table class="table table-bordered">
<thead>
<th>Item Barcode</th>
<th>Quantity</th>
<th>Cost Price</th>
<th style="text-align: center;background: #eee">
<a href="#" onclick="addRow()">
<i class="glyphicon glyphicon-plus"></i>
</a>
</th>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="itemid">
<option value="" selected disabled>Select Barcode</option>
#foreach($items as $item)
<option value="{{$item->itemid}}">{{$item->itembarcode}}</option>
#endforeach
</select>
</td>
<td><input type="text" name="quantity" class="form-control quantity"></td>
<td><input type="text" name="costprice" class="form-control costprice"></td>
<td style="text-align: center" onclick="cannotdelete()">
<a href="#" class="btn btn-danger remove">
<i class="fa fa-times"></i>
</a>
</td>
</tr>
</tbody>
</table>
<br>
<button type="submit" class="btn btn-primary pull-right">Submit</button>
</div>
<script type="text/javascript">
function addRow()
{
var tr='<tr>'+
'<td>'+
'<select class="form-control" name="itemid">'+
'<option value="" selected disabled>Select Barcode</option>'+
'#foreach($items as $item)'+
'<option value="{{$item->itemid}}">{{$item->itembarcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="quantity" class="form-control quantity"></td>'+
'<td><input type="text" name="costprice" class="form-control costprice"></td>'+
'<td class="remove" style="text-align: center"><i class="fa fa-times"></i></td>'+
'</tr>';
$('tbody').append(tr);
}
function deleteRow()
{
$(document).on('click', '.remove', function()
{
$(this).parent('tr').remove();
});
}
function cannotdelete()
{
alert('You cannot delete the first row!!!')
}
</script>
My controller:
public function save(GoodsreceiveheaderRequest $request)
{ $data = array(
'referencenumber'=>$request->referencenumber,
'vendorid'=>$request->vendorid,
'date'=>$request->date,
'createdby'=>$request->createdby,
);
$i = DB::table('goodsreceiveheader')->insertGetId($data);
$goodsreceivedetail = array(
'goodsreceiveheader_id'=>$i,
'itemid'=>$request->itemid,
'quantity'=>$request->quantity,
'costprice'=>$request->costprice,
);
$s = DB::table('goodsreceivedetail')->insert($goodsreceivedetail);
Session::flash('message','You have successfully create goods receive.');
return redirect('goodsreceive/goodsreceiveheader_list');
}
use insert function and pass your data as multiple array like
if model name is 'User' then below code will work for multiple entry
User::insert(['name'=>'xyz'],['name'=>'abc']);
Solved.
public function save(GoodsreceiveheaderRequest $request)
{
$head = Goodsreceiveheader::findorNew($request->id);
$head->referencenumber=$request->referencenumber;
$head->vendorid=$request->vendorid;
$head->date=$request->date;
$head->createdby=$request->createdby;
if ($head->save()){
$id = $head->id;
foreach($request->itemid as $key =>$item_id){
$data = array(
'goodsreceiveheader_id'=>$id,
'itemid'=>$request->itemid [$key],
'quantity'=>$request->quantity [$key],
'costprice'=>$request->costprice [$key],
);
Goodsreceivedetail::insert($data);
}
}
Session::flash('message','You have successfully create goods receive.');
return redirect('goodsreceive/goodsreceiveheader_list');
}

Categories

Resources