how to save table data of dynamic row into database using laravel - javascript

I am creating a table with one rows which contain two input fields as friend_name and Contact_no , and a buttons as "add contact" when user click on add contact then again a row create but with only one column as contact no. so user can add multiple contact for single friend and save it into database. this is done for one friend with multiple contact_no. at a time very easily.
i am created for only one friend with multiple contact at a time as follow
<form action "..." mehtod="post">
<table id="table1">
<thead>
<tr>
<th>friend</th>
<th>Contact No.</th>
</tr>
</thead>
<tbody>
</table>
<button id="addcontact" type="button" float: right;" onclick="addcontact()">add contact</button>
<button id="deletecontact" type="button" float: right;" onclick="deletecontact()">delete contact</button>
<input type="submit" value="submit" name="submit">
</form>
<script>
function addcontact() {
document.getElementById("table1").insertRow(-1).innerHTML = '<td> <input type="hiddden"> </td><td> <input type="text" name="contact_no[]"></td>';
}
function deletecontact() {
var table = document.getElementById('table1');
var rowCount = table.rows.length;
table.deleteRow(rowCount -1);
}
<script>
and my controller is...
public function addfriendcontact(Request $request)
{
$count = count(Input::get('contact_no'));
for($i = 0; $i<$count; $i++)
{
$friend = new Friend;
$friend->name = $request->name;
$friend->contact_no = $request->contact_no[$i];
$friend->save();
}
return back();
}
but i want to create multiple friends and multiple contact of that friends at a time and save that data into database using laravel how can i do that.

1) You need to post your Form by adding in your action attribute one link. Also adding the csrf field. Because it protects your application from cross-site request forgery (CSRF) attacks. Without that, it will throw an error.
<form action="/contacts/insert-contact" mehtod="post">
{{ csrf_field() }}
2) You need to add this line to your web.php file. Note that the ControllerName must be your Actually Controller
Route::post('contacts/insert-contact','ControllerName#addfriendcontact');
3) Now in the Controller your have to insert your method. And that's it.
I hope it helps. :)

Related

How to insert multiple rows of data from dynamically generated rows into a database using Python Django

I have a Javascript function (addItem) that allows a user to add any number of dynamically generated rows of data and fill in the necessary fields required. See code below
<div class="modal-body">
<table class="table order-list table-striped" id="myTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="addItems">
</tbody>
</table>
<table>
<tbody>
<tr>
<td colspan="5" style="text-align: left;">
<button onclick="addItem();" class="btn btn-sm btn-success" id="sspusd1" value="Add Row"><i class="fa fa-plus"></i>Add Row</button>
</td>
<td colspan="5" style="text-align: left;">
</td>
</tr>
</tbody>
</table>
</div>
function addItem() {
renumber++;
var html = "<tr>";
html += "<td><select class='form-control'>{% for stock in stocks %}<option class='dropdown-item' value='{{stock.inventoryPart}}'>{{stock.inventoryPart}}</option>{% endfor %}</select></td>";
html += "<td><input type='number' class='form-control' onblur='lineTotal(this);' value='0' name='quantity[]'/></td>";
html += "<td><input type='text' class='form-control' onblur='lineTotal(this);' value='0' name='price[]'/></td>";
html += "<td><input type='text' id='lineTotal' class='form-control' value='0' disabled name='total[]' /></td>";
html += "</tr>";
document.getElementById("addItems").insertRow().innerHTML = html;
};
However, One is able to insert any number of rows they want and insert the necessary data into the fields available.
The problem is that I am unable to capture and store the dynamic information entered into these dynamic rows since Django is unaware of how many rows a user has created.
The aim is to be able to store the data from the created dynamic rows inserted by the user, into the database using Django
Below is the code from my views
def customers(request):
if request.method == 'POST':
if 'Receipttotal' in request.POST:
stocksArr = request.POST.getlist('stock')
quantityArr = request.POST.getlist('quantity')
priceArr = request.POST.getlist('price')
totalArr = request.POST.getlist('total')
print("---Array Data---")
print(stocksArr)
print(quantityArr)
print(priceArr)
print(totalArr)
So the print statements output an empty list.
How possible is this functionality? I would like assistance on this.
Thanks.
The best solution I see is using formsets with HTMX. You can follow this excellent tutorial https://justdjango.com/blog/dynamic-forms-in-django-htmx
I suppose you have, somewhere in your html, a form like this:
<form action="" method="post">
<!-- Your table etc. here -->
</form>
In this case, try to modify your view in this way:
if request.method == 'POST':
stocksArr = request.POST.getlist('stock')
quantityArr = request.POST.getlist('quantity')
priceArr = request.POST.getlist('price')
totalArr = request.POST.getlist('total')
print("---Array Data---")
print(stocksArr)
print(quantityArr)
print(priceArr)
print(totalArr)
Now, probably your form wasn't finding if 'Receipttotal' in request.POST:. Try this way and let me know if that solves your issue.

Update array data when clicking outside input

Cordial greetings I am developing a project in Laravel where I perform a data update in a table dynamically, this data is an array that is created by selecting an item and the function I perform is that when I click on the green button updates the data entered in the array.
But a requirement that they have asked me is that the green button is not there, that when entering the data in the input and clicking outside the input, it updates automatically. To update my data I do it this way, This is my table
<table class="table table-bordered">
<tr>
<th style="font-size: 11.7px;">Item</th>
<th style="font-size: 11.7px;">Eliminar</th>
</tr>
#foreach ($cart as $servicio)
<tr>
<td style="font-size: 11.7px;">
<input type="text"
class="form-con-lg"
value="{{$servicio->n_item}}"
id="servicio_{{$servicio->id}}">
<a class="btn-update-item btn btn-success"
data-href="{{ route('servicio_update',$servicio->id)}}"
data-id="{{$servicio->id}}">
<i class="fas fa-sync-alt"></i>
</a>
</td>
<td>
<i class="fas fa-trash-alt"></i>
</td>
</tr>
#endforeach
</table>
and this is my script where I pass the data to update my array
<script type="text/javascript">
$(document).ready(function(){
$(".btn-update-item").on('click', function(e){
e.preventDefault();
var id = $(this).data('id');
var href = $(this).data('href');
var n_item = $("#servicio_" + id).val();
swal("Good job!", "You clicked the button!", "success");
window.location.href = href + "/" + n_item;
});
});
</script>
and my controller where I update my array
//UPADTE
public function update(Servicios $servicios,$n_item){
$cart = Session::get('cart');
$cart[$servicios->id]->n_item = $n_item;
Session::put('cart', $cart);
return redirect()->route('coti_show');
}
and my route
Route::get('/servicios/update/{servicios}/{n_item?}', 'Admin\CotizacionController#update')->name('servicio_update');
I would like to know how I can do that when I enter the data in the input and click outside the input it is automatically updated, thank you for your help.
As Bravo said, a blur handler could be used, and would probably be the most straightforward. The other route would be to add a click handler to the window (or some encapsulating parent within which you want to check for clicks) and check that the Event.target.id (or some other property of your liking) does not match that of the input.
That being said, the blur handler is most likely the more straightforward solution, just presenting alternatives.

Sending selective data from dynamic table

I have a dynamic table with some data and total counting with JS, when checkbox is ticked row is removed from count.
I need a way to send first ID field and total price to another php page for rows where checkbox is ticked.
As seen on picture below I need to send vales 8, 10 and 15 with total 1500.
I have given every checkbox an unique id and value of same id.
<table id="price-list">
<tr>
<td>Some data</td>
<td>
<input class="w3-check" type="checkbox" checked="" value="<?php echo $row['rad_id']?>" id="<?php echo $row['rad_id']?>">
</td>
</tr>
<tfoot>
<tr class="totalColumn">
<td><span> Ukupno:</span></td>
<td class="total price">0.00 kn</td>
</tr>
</tfoot>
</table>
Closest that I got is reading whole table with JS, with another script putting it into submit value and passing it into another PHP page.
<form action="spec-provjera.php" method="POST">
<input type="button" id="bt" value="Show Table Data" onclick="showTableData()" />
<!-- <input type="submit" name="submit" value="info" id="info" onclick="myFunction()"/> -->
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('price-list');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.value = info.innerHTML + '<br />'; // ADD A BREAK (TAGG)
}
}
</script>
<script>
function myFunction() {
var info = document.getElementById("info").value;
$.ajax({
type : "POST", //type of method
url : "spec-provjera.php", //your page
data : { info : value.info},// passing the values
success: function(res){
//do what you want here...
}
});
}
</script>
<button class="w3-btn w3-right w3-deep-orange" type="submit" name="izrada" id="info" onclick="myFunction()"/>KREIRAJ test</button>
</form>
This passes all table contains into spec-provjera.php with AJAX but this way is totally messy and posts all rows with check-boxes all set too checked.
Id be happy if I could just filter out cheeked row's.
Can someone suggest a way to do this, keep in mind I'm not very good with JS.
Found a solution:
I wrapped whole table as form then made dynamic checkbox unique field and same value "da" like this:
<input class="w3-check" type="checkbox" checked="" name="<?php echo $row['rad_id']?>" value="da">
Also made an total price field an input with read only like this:
$("tfoot .total.price",tbl).html( '<input type="post" id="total" readonly size="5" value="' + t.toFixed(2) + '" name="total"> kn');
Then I'm doing on other PHP page this:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'</br> " ;
}
Witch if i uncheck id 14 as seen on first picture gives me:
POST parameter '8' has 'da'
POST parameter '10' has 'da'
POST parameter '15' has 'da'
POST parameter 'total' has '1500.00'
As seen i have only checked items with total price. Now i can manipulate this as needed in PHP.

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

mapping wrong number of rows from a table in jsp in Struts2

I am working on a Struts2 application and facing a unique issue for which i need your help. The scenario is as below. I am also using Bootstrap for the same.
I have a form as below sample. In the page i can dynamically add New Rows to this form with the New button.
<form method="post" id="mainForm" action="editForm"/>
<body onload="Rows()">
<table id="mainTable" class="table table-striped table-hover table-condensed" cellspacing="0" width="100%">
<thead>
<tr>
<th>ProcessName</th>
<th>PDate</th>
<th>Description</th>
</tr>
</thead>
<tbody id="Row">
<s:iterator value="list" var="voDetails" status="rowStatus">
<tr>
<td><input size="8" value="<s:property value="processName" />"/></td>
<td><input size="8" value="<s:date name="date_dt" format="MM/dd/YYYY"/>"/> </td>
<td><input size="8" value="<s:property value="description"/>"/></td>
</tr>
</s:iterator>
</tbody>
<button type="button" class="btn btn-primary btn-xs" onclick="Save()">Save</button>
<button type="button" class="btn btn-primary btn-xs" onclick="AddNewRow()">AddNewRow</button>
<button type="button" class="btn btn-primary btn-xs" onclick="Close();">Cancel</button>
The Javascript function Save is as below
function Save()
{
document.forms[0].action = click_save_buttom';
document.forms[0].submit();
}
function AddNewRow()
{
// code to add row dynamically to the page
}
function Rows(){
rows = document.getElementById("Row").rows.length;
for (i = 0; i < rows ; i++) {
var row = document.getElementById("Row").rows[i];
row.setAttribute("rowNum", i);
//alert("ROW: " + i);
for (j = 0; j < 3; j++) {
if(document.getElementById("listSize")!=null || rows > 1)
row.cells[j].children[0].setAttribute("name", "list[" + i + "]." + names[j]);
}
}
}
When i sumbit this form the values are getting mapped to the action and Save is working properly. Save also works when i dynamically add new row to the form.
The issue is that sometimes when this page has for example 1 row and i dynamically add a new row and totally there are 2 rows in the form table. When i submit the form then additional more than 2 rows(mapped to VO's in action) are being passed to the action. These additional rows are present in the previous page which is having a similar form table from where i select a row and land on the current page. The save function is happening for these additional rows(VO's) and after save when the page re loads these additional rows appear in the table.
Not sure why this is happening. I checked the number of rows in the table by putting an alert in Save function and it shows 2 as the length before the form submission. It is after the form submission that additional rows(VO's in action) are being mapped to action.
Can you please help me resolve this issue as i am stuck with it for a very long time now.
Thanks
Vikeng
New Edit: Ok, to me it looks like your issue is how you are looping. The rows value gives you an accurate number of rows- but you are looping starting with zero until you're greater than the number of rows it returns (would be two extra... which is accurately the problem you describe) Try this instead:
for (i = 1; i = rows ; i++) {
OLD Edit: Maybe try to call your form by id instead of by form index and see if somehow the form index could be causing the issue in the browser you are working in?
document.getElementById("mainForm").action = click_save_button;
document.getElementById("mainForm").submit();
.. and make sure you correct your click_save_button typo, if it is a typo.
OLD: It is very unclear what you are doing here:
document.forms[0].action = click_save_buttom';
Do you have a code you are running in a document called 'click_save_buttom' ? I believe this adds a form action to the first form on the page... like
<form action='click_save_buttom'></form>
Also instead of using form index, its better to give the form an id. Instead of submitting a form this way:
document.forms[0].submit();
consider submitting a form by using button type=submit

Categories

Resources