PHP POST Array from window-modal - javascript

I have a web page that contain a table. Every rows has a checkbox. When the user select the rows, using checkbox, and push a button(I save the codes in array) It show a window-modal with four buttons(input). When click one of this buttons it launch a PHP page to update database.
Now when it showed the window modal I get an array with the codes of the selections rows and I do not know how to send this array(jquery code) to PHP page using POST method.
HTML code of window-modal:
<!-- CHANGE STATUS MODAL MENU -->
<div class="modal fade" id="change" tabindex="-1" role="dialog" aria-labelledby="change" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">CANVIAR ESTAT</h3>
</div>
<form action="updateEstado.php" method="post">
<div class="modal-body">
<div class=" text-center">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" class="btn btn-modal-estado" style="background-color:YellowGreen; color:white;" value="ACTIVAT">
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" class="btn btn-modal-estado" style="background-color:Tomato; color:white;" value="PENDENT MIQUEL ALIMENTACIÓ">
</div>
</div>
<div class="row ">
<div class="col-md-12 text center">
<input type="submit" class="btn btn-modal-estado" style="background-color:SkyBlue; color:white;" value="PENDENT ADDCOM">
</div>
</div>
<div class="row">
<div class="col-md-12 text center">
<input type="submit" class="btn btn-modal-estado" style="background-color:Gray; color:white;" value="DESACTIVAT">
</div>
</div>
<div class="row">
<h5 id='codigosSeleccionados'></h5>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Jquery code:
/* CHANGE MODAL WINDOW */
$('#change').on('show.bs.modal', function (event) {
var arrayCod = new Array();
$('#tableprod').find('tbody tr').each(function () {
var $button = $(event.relatedTarget) // Button that triggered the modal
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var field = $(this).data("field");
var cod;
$tds = row.find("td"); // get all table cells in that row
$.each($tds, function(index,value) {
var field = $(this).data("field");
if (field == 'codigo'){
cod = $(this).text();
console.log(cod);
arrayCod.push(cod);
return false;
}
});
}
if (arrayCod.length != 0){
$('input[type="submit"]').prop('disabled', false);
$('#codigosSeleccionados').text(arrayCod.length + " codis seleccionats");
} else {
$('input[type="submit"]').prop('disabled', true);
$('#codigosSeleccionados').text("Cap codi seleccionat");
}
});
//$('#codigosSeleccionados').text("CODIS SELECCIONATS: " + strCods);
console.log(arrayCod.length);
});
And PHP page:
$conn = dbConnect("localhost", "5432", "dbname", "dbuser", "dbpass");
$codigo = $_POST['codigo'];
$query = "UPDATE produccion.ma_producto SET estado={$estado} WHERE codigo={$codigo}";
$result = pg_query($conn, $query);
I'm not sure to how do it, Could I save in global php variable from jquery? Or Could I send the array with method post when it click on button? :(

Add all checked codes as a list of hidden fields with [], then PHP will receive them as a list as well. It should be on a form which one of those 4 buttons of the modal will submit:
var $form = $("form"); // The modal's form
arrayCod.forEach(function(cod) {
$('<input type="hidden" name="codigo[]" value="' + cod + '">').appendTo($form);
});
// Event handler for your modal's four buttons. They will submit the form
$('.modal').on('click', 'button', function() {
$form.submit();
});
Then in PHP:
$codigos = $_POST["codigos"]; // This will be an array
Example:
$("#open-modal").on("click", function() {
var checkedCodes = [];
// Get checked checkboxes
$("#codes input").each(function() {
if ($(this).is(":checked")) {
// Get the code from td's text
checkedCodes.push($(this).closest("tr").find("td:eq(1)").text());
}
});
// Add hidden fields to the "modal"'s form
var $modal = $("#modal-body"),
$form = $modal.find("form");
checkedCodes.forEach(function(code) {
$('<input type="hidden" name="codigos[]" value="' + code + '">').appendTo($form);
});
$modal.show();
});
$("#modal-body").on("click", "button", function() {
$("#modal-body").find("form").submit();
});
#modal-body {
display: none;
border: 1px solid #000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="codes">
<tr>
<td><input type="checkbox"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>3</td>
</tr>
</table>
<button id="open-modal">Open Modal</button>
<div id="modal-body">
Imagine this is your modal
<form>
<button>Button #1</button>
<button>Button #2</button>
<button>Button #3</button>
<button>Button #4</button>
</form>
</div>
This code is just an example. I didn't even based it over your code.

Related

What's the correct way to submit a single element in a list when each of them has a separate submit button

I have an event page which contains a list of participants. From there users can be invited to that event by opening a modal view containing a user list. Users are shown in the same modal with each having an 'Invite'(submit) button next to them. How can I let the controller action know which user is invited?
From what I could find, creating a form for each list element is bad and in addition displays warnings, but if I create a form element on top of the 'foreach', I then need to somehow find which user to submit.
Also thought about appending incrementing numbers to each of submit button name, but I still need to somehow map them to 'their' users.
Along with the invited user id, controller post action also needs to receive the event id.
Here's the code:
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select user</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="eventMemberForm" method="post" class="col-sm-6 custom-close" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-url="#Url.Action("SendInvitation", "Sports")">
<input type="hidden" asp-for="Invitation.FkEvent" value="#Model.Event.EventId" />
<input type="hidden" asp-for="Invitation.EventInvitationId" />
<div class="modal-body">
<input class="form-control p-2 mb-2" id="myInput" type="text" placeholder="Search..">
<h4 class="align-content-center">Users</h4>
<div class="form-group">
<table class="w-100">
<tbody id="myField">
#foreach (var item in Model.Users)
{
<tr>
<td class="d-flex">
<div> #Html.DisplayFor(modelItem => item.Text) </div>
<input type="hidden" asp-for="Invitation.FkUser" value="#item.Value" />
<div class="ml-auto">
<input id="btnSave" type="submit" value="Invite" class="btn btn-success" />
</div>
</td>
</tr>
++i;
}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myField tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
completed = () => {
alert("User invited");
};
</script>
You can use jquery ajax to pass the parameters you need, through the click event, get the corresponding value of the control needed next to the current button.
By adding the name attribute to the submit button, and then triggered in jquery.
And add the id to the div that stores the Text value of User to facilitate finding the corresponding value in jquery.
#section Scripts{
<script>
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myField tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$("[name=submitBtn]").click(function () {
event.preventDefault();
var obj = {
myUser: {
Text: $($(this).parent().siblings()[0]).text(),
Value: $($(this).parent().siblings()[1]).val()
},
eventId: $("#Invitation_FkEvent").val()
};
$.ajax({
url: $("#eventMemberForm").attr("data-ajax-url"),
method: 'post',
data: obj,
})
});
});
completed = () => {
alert("User invited");
};
</script>
}
<h1>Index</h1>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary">Submit</button>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select user</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="eventMemberForm" method="post" class="col-sm-6 custom-close" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-url="#Url.Action("SendInvitation", "Sports")">
<input type="hidden" asp-for="Invitation.FkEvent" value="#Model.Event.EventId" />
<input type="hidden" asp-for="Invitation.EventInvitationId" />
<div class="modal-body">
<input class="form-control p-2 mb-2" id="myInput" type="text" placeholder="Search..">
<h4 class="align-content-center">Users</h4>
<div class="form-group">
<table class="w-100">
<tbody id="myField">
#foreach (var item in Model.Users)
{
<tr>
<td class="d-flex">
<div id="textValue"> #Html.DisplayFor(modelItem => item.Text) </div>
<input type="hidden" asp-for="Invitation.FkUser" value="#item.Value" />
<div class="ml-auto">
<input id="btnSave" type="submit" value="Invite" class="btn btn-success" name="submitBtn"/>
</div>
</td>
</tr>
++i;
}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
Controller:
public IActionResult SendInvitation(User myUser, string eventId)
{
//do what you want
return View();
}

How to create a simple edit button on crud?

i'm trying to make a simple Crud for my homework . most of my code works properly for the most part, except the edit button. it only edits the first row. below, i provide my TS code along with my HTML. for the HTML i'm using Modal windows. so everytime i click on the edit buttons. a modal will appears
function create() {
let user: string = String($("#username").val());
let data: JQuery = $("<tr id='crudData'><td>" + user + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crud").append(data);
}
function edit() {
let user2: string = String($("#username2").val());
let data2: JQuery = $("<tr id='crudData'><td>" + user2 + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crudData").replaceWith(data2);
}
$("#userbstg").on("click", create);
$("#saveEdit").on("click", edit);
<section>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3 class="section-heading">Aufgabe - Usermanager</h3>
<label for="username">Username:</label>
<input id="username" class="form-control col-md-3" type="text">
<button id="userbstg" class="btn btn-info">Add</button>
<table id="crud" class="col-md-4 table">
<tr>
<th class="col-2" id="user">User</th>
<th class="col-2" id="edit"></th>
</tr>
</table>
</div>
</div>
</div>
<div class="modal fade" id="crudModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<label for="username2">Username:</label>
<input id="username2" class="form-control col-md-12" type="text">
<button type="button" id="saveEdit" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
</section>

input hidden value doesn't send to controller

I'm trying post to my database,everything what i want i can get from my formcollection and my table but input hidden value.My main view is using #model List
Here is my code this my modal popup
#using (Html.BeginForm("update3", "UpdateInfo", FormMethod.Post))
{
<div class="modal fade" role="dialog" id="mymodal">
<form id="stok_formu">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modal2">
<div class="row">
<label for="names" id="name" name="name"></label>
<input type="hidden" id="names" name="names" />
</div><br />
<div class="row">
<div class="col-md-3">
#Html.Label(" Clothes codes: ")
</div>
<div class="col-md-3">
<input type="number" class="input-sm" id="codes" name="codes" />
</div>
</div><br />
<div class="row">
<div class="col-md-3">
#Html.Label("New Price : ")
</div>
<div class="col-md-3">
<input type="number" class="input-sm" id="newprice" name="newprice" />
</div>
</div>
<input class="btn btn-success" id="change" type = "submit" name="change"/>
</div>
</div>
</div>
</form>
</div>
}
With this javascript code ,i can get my "name" from my table and put on my modal and my problem is begin is here,when i click button submit modal popup doesn't send hidden value to controller but ican get my value of "newprice"
function metot(x) {
namee = document.getElementById("tablo2").rows[0].cells.item(0).innerHTML;
document.getElementById("name").innerHTML = namee;
}
and table from my main view
<tbody id="tablo2">
#foreach(var oge in Model)
{
<tr onclick="metot(this)">
<td>#Html.Encode(oge.name)</td>
<td id="codes">#Html.Encode(oge.codes)</td>
<td id="price">#Html.Encode(oge.price)</td>
<td>
<button id="change" onclick="metot(this)" type="button" data-toggle="modal" data-target="#mymodal" class="btn btn-warning tab-content"><span>Change</span></button>
</td>
</tr>
}
</tbody>
You are setting the text of the label with id name, but you aren't setting the value of the hidden field with id names, hence it is not sent when you submit the form. <label> elements do not send data back to the server.
This should work (I assume the variable namee should actually be called urun_adi):
function metot(x) {
urun_adi = document.getElementById("tablo2").rows[0].cells.item(0).innerHTML;
document.getElementById("name").innerHTML = urun_adi;
document.getElementById("names").value = urun_adi;
}

Modal in Asp.NET MVC

I have a Asp.NET MVC application, i trying to use a modal to make the update of the data, i have two modal for Register and Update, the Register is OK, but the Update is not working, when a click on the "Alterar" button, need to open a modal with the data filled, i trying to use JavaScript to do this.
Can someone help me?
My table
My modal that need open filled with data
My Code
Table
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Produto</th>
<th>Custo</th>
<th>Lucro</th>
<th>Opcoes</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach(var sale in Model)
{
<tr>
<td>#Html.DisplayFor(model => sale.idProduct)</td>
<td>#Html.DisplayFor(model => sale.nameProduct)</td>
<td>#Html.DisplayFor(model => sale.costProduct)</td>
<td>#Html.DisplayFor(model => sale.profitProduct)</td>
<!--Get values to put on Modal-->
<td><a class="update" data-toggle="modal" href="#updateModal" data-id="#sale.idProduct" data-name="#sale.nameProduct"
data-cost="#sale.costProduct" data-profit="#sale.profitProduct"><span class="glyphicon glyphicon-edit">Alterar</span></a></td>
</tr>
}
}
</tbody>
</table>
enter code here
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var $this = $(this);
var idProduct = $this.data('id');
var nameProduct = $this.data('name');
var costProduct = $this.data('cost')
var profitProduct = $this.data('profit')
$('#nameProduct').text(nameProduct);
$('#costProduct').text(costProduct);
$('#profitProduct').text(profitProduct);
$("#updateModal #form_update #idProduct").val(idProduct);
$('#updateModal').modal();
});
});
Modal
<div id="updateModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal">×</button>
<h4 class="modal-title">Alterar Produto<span id="name_product"></span></h4>
</div>
<form method="post" id="form_update" action="/Dashboard/Product">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name="idProduct" id="idProduct" class="form-control" placeholder="ID do produto"/>
<input type="text" name="nameProduct" id="nameProduct" class="form-control" placeholder="ID do produto" required />
<input type="text" name="costProduct" id="costProduct" class="form-control" placeholder="Custo do Produto" required />
<input type="text" name="profitProduct" id="profitProduct" class="form-control" placeholder="Lucro do Produto" required />
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" value="Atualizar" />
<button type="button" class="btn btn-warning" data-dissmiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
to change the value of input you need to use val() :
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var $this = $(this);
var idProduct = $this.data('id');
var nameProduct = $this.data('name');
var costProduct = $this.data('cost')
var profitProduct = $this.data('profit')
$('#nameProduct').val(nameProduct);
$('#costProduct').val(costProduct);
$('#profitProduct').val(profitProduct);
$("#updateModal #form_update #idProduct").val(idProduct);
$('#updateModal').modal();
});
});
Your modal contains only inputs.
For setting the value of input you used $('#nameProduct').text(nameProduct) and that's the wrong thing. You need the val() method.
$('#nameProduct').val(nameProduct);
.text() method is used specially for div, span, etc.
UPDATE
<td>#Html.DisplayFor(model => sale.idProduct)</td> generates a span with the follow properties: id and name have value idProduct. The problem is that you have two elements with same id(in table and in modal). id attribute must be unique in DOM.
Modal
<div id="updateModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal">×</button>
<h4 class="modal-title">Alterar Produto<span id="name_product"></span></h4>
</div>
<form method="post" id="form_update" action="/Dashboard/Product">
<div class="modal-body">
<div class="form-group">
<input type="hidden" class="form-control modalInput" placeholder="ID do produto"/>
<input type="text" class="form-control modalInput" placeholder="ID do produto" required />
<input type="text" class="form-control modalInput" placeholder="Custo do Produto" required />
<input type="text" class="form-control modalInput" placeholder="Lucro do Produto" required />
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" value="Atualizar" />
<button type="button" class="btn btn-warning" data-dissmiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var modal=$('#updateModal');
var idInput = modal.find('input.modalInput').eq(0);
var nameInput = modal.find('input.modalInput').eq(1);
var costInput = modal.find('input.modalInput').eq(2);
var profitInput = modal.find('input.modalInput').eq(3);
idInput.val($(this).data('id'));
nameInput .val($(this).data('name'));
costInput.val($(this).data('cost'));
profitInput .val($(this).data('profit'));
modal.modal();
});
});
</script>
HTML
foreach(var sale in Model)
{
<tr>
<td>#Html.DisplayFor(model => sale.idProduct)</td>
<td>#Html.DisplayFor(model => sale.nameProduct)</td>
<td>#Html.DisplayFor(model => sale.costProduct)</td>
<td>#Html.DisplayFor(model => sale.profitProduct)</td>
<!--Get values to put on Modal-->
<td><a class="update" data-id="#sale.idProduct" data-name="#sale.nameProduct" data-cost="#sale.costProduct" data-profit="#sale.profitProduct"><span class="glyphicon glyphicon-edit">Alterar</span></a></td>
</tr>
}
you must use val().You use like a text("asda").you change these problem resolve

Get values from bootstrap modal, process then insert value to database

I am using table where values are printed from database. Then I make selections. After that I want to process those values together with values from bootstrap modal which are required to fill. Once I get all values, I need to store them into database.
Table store values from database:
<table id="table" class="table table-bordered table-striped">
<thead>
<tr class="bg-red">
<th>Id</th>
<th>Material</th>
<th>Quality</th>
<th>Dimensions</th>
<th>Colors</th>
<th>Weight</th>
<th><center><i class="fa fa-shopping-cart"><center></th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?='B-'. $r['Id']?> </td>
<td> <?=$r['Material']?> </td>
<td><?=$r['Quality']?></td>
<td><?=$r['Dimensions']?></td>
<td><?=$r['Colors']?></td>
<td><?=$r['Weight']?></td>
<td> <button class="addValues" name="code[]" value="<?='B-'. $r['Id']?>"><i class="fa fa-shopping-cart"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Then I am using script make row selection and print values to another div (This section works)
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = (' <input type="text" name="quantity[]" placeholder="kg / m" size="10"/>');
targetArea.prepend($("td.data-id", myRow).text() + qte_input +"<hr />");
});
</script>
Output in div after row is selected (Multiple selections could be chosen)
B-15897 3000kg // B-15897 presents code 3000kg presents quantity.
B-4589 500m
Below those values I have submit button, which opens bootstrap modal.
<div class="col-xs-2">
<div class="box box-danger">
<h4>Selected: </h4><br/>
<div id="selection">
<!-- SELECTED VALUES -->
B-15897 3000kg
B-4589 500m
</div>
<button class="btn btn-block bg-red btn-sm" data-toggle="modal" data-target="#myModal">Send request</button>
</div>
</div>
Once I hit Send request it opens bootstrap modal:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" href="repromaterijali-script.php">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Offer request</h4>
</div>
<div class="modal-body">
* Company name
<input type"text" class="form-control" name="company" required><br/>
* Contact info
<input type"text" class="form-control" name="contact" required><br/>
* Adress
<input type"text" class="form-control" name="address" required><br/>
* Phone
<input type"text" class="form-control" name="tel"required><br/>
E-mail
<input type"text" class="form-control" name="email" ><br/>
Other
<textarea type"text" class="form-control" name="other" ></textarea><br/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" name="submit">Send</button>
</div>
</div>
</div>
</div>
I want to pick all values from bootstrap modal and from div where selected values are, process them and insert in database via php. code and quantity will be an array because multiple values could be selected.
Bootstrap modal and div where selected values are inside <form>. I am trying to get values by using script bellow but nothing happens:
<script type="text/javascript">
function get_values() {
var x = document.getElementById("quantity").value;
var y = document.getElementById("code").value;
var arr = {barcode:x};
$.ajax({ url: 'insert.php',
data: arr,
type: 'post',
success: function(output) {
document.getElementById("code").value = output;
}
});
}
</script>
I am looking for advice? Any kind of help is very appreciated.
Your modal isn't coded correctly on a couple of levels.
First, the input elements do not have an id assigned. Normally one would get the value via the id. In a similar way you did here:
var x = document.getElementById("quantity").value;
Also, while it has nothing to do with reading the values from the modal, from a Bootstrap perspective, your input form is not coded the way the Bootstrap CSS expects it to be coded.
Here an example from the Bootstrap site:
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
Notice each input is wrapped in a form-group. If you use this layout, you'll not need to use the <br> tag.

Categories

Resources