Get Textbox value from bootstrap modal dynamically - javascript

I have a table that will retrieve all the users information along with a button that will open a popup modal to edit the user details. The Modal will display the user data correctly , but when I try to save the changes that the user has entered on a button click, the value of the textboxes will be the first row of the table bot the one that the user entered. How can I get the value of the textbox that is currently displayed on the modal popup.
My View:
<div class="form-group" align="center">
<table id="AllUsersTable2" class="display" style="width:100%;">
<tr>
<th>id</th>
<th>FullName</th>
<th>username</th>
<th>MobileNumber</th>
<th>Email</th>
<th>IsActiveText</th>
<th>RoleName</th>
<th>Edit</th>
</tr>
#foreach (var user in Model.UserTable)
{
<tr>
<td>#user.NationalID</td>
<td>#user.FullName</td>
<td>#user.username</td>
<td>#user.MobileNumber</td>
<td>#user.Email</td>
<td>#user.IsActiveText</td>
<td>#user.RoleName</td>
<td><button class="btn btn-primary" id="" data-toggle="modal" data-target="##user.NationalID">عرض</button></td>
</tr>
//PopUp Starts HERE
<div class="modal fade" id="#user.NationalID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title" id="test2" style="text-align: right;"> بيانات المستخدم</h1>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
#using (Html.BeginForm(Html.BeginForm(null, null, FormMethod.Post, new { #id = "UpdateUserForm" })))
{
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="NationalID" class="control-label">رقم الهوية</label>
<input type="text" id="UpdateuNationalID" name="NationalID" value="#user.NationalID" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="FullName" class="control-label">الإسم</label>
<input type="text" id="UpdateFullName" name="FullName" value="#user.FullName" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="username" class="control-label">اسم المستخدم</label>
<input type="text" id="Updateusername" name="username" value="#user.username" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="MobileNumber" class="control-label">رقم الهاتف</label>
<input type="text" id="UpdateMobileNumber" name="MobileNumber" value="#user.MobileNumber" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Email" class="control-label">البريد الإلكتروني</label>
<input type="text" id="UpdateEmail" name="Email" value="#user.Email" class="control-label">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="IsActive" class="control-label">حالة المستدم</label>
<select name="IsActive" id="UpdateIsActive">
<option value="">...</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="RoleId" class="control-label">البريد الإلكتروني</label>
<select name="RoleId" id="UpdateRoleId">
<option value="">...</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
</div>
</div>
</div>
</div>
}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn">تعديل المستخدم </button>
</div>
</div>
</div>
</div>
//PopUp END HERE
}
</table>
</div>
My Click Event:
$('body').on('click', '.UpdateUserBtn', function (e) {
var NationalID = $("#UpdateuNationalID").val();
console.log(NationalID);
var username = $('#Updateusername').val();
var FullName = $('#UpdateFullName').val();
var MobileNumber = $('#UpdateMobileNumber').val();
var Email = $('#UpdateEmail').val();
var RoleId = $('#UpdateRoleId').val();
var IsActive = $('#UpdateIsActive').val();
$.post("#Url.Action("UpdateUser", "Home")", { NationalID: NationalID, username: username, FullName: FullName, MobileNumber: MobileNumber, Email: Email, RoleId: RoleId, IsActive: IsActive }, function (data) {
if (data.Result == 1) {
//closePopup();
$.notify(
"تم الحفظ بنجاح",
{
globalPosition: 'top center',
className: 'success'
}
);
}
else {
console.log(data);
$.notify(
"حدث خطأ أثناء الحفظ ",
{
globalPosition: 'top center',
className: 'danger'
}
);
// console.log(data);
}
});
});
The problem here for example the value of $("#UpdateuNationalID").val(); will be always the value of first row of the table not the value that is displayed on the popup..

The problem as said by #Carsten Løvbo Andersenis is that you are using the same Id when generating the HTML, so your jQuery var NationalID = $("#UpdateuNationalID").val(); will take the first value that he find.
To solve this, you need to assign a different Id in every loop, for example you can do ad follow if we suppose that NationalID is unique :
<input type="text" id='UpdateuNationalID #user.NationalID' name="NationalID" value="#user.NationalID" class="control-label" required>
EDIT:
You have to create a function for example SaveMe instead to wait for the event click, and you need to send a value on click in your modal:
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn" onclick="SaveMe(#user.NationalID)">تعديل المستخدم </button>
and your event listner first line $('body').on('click', '.UpdateUserBtn', function (e) {
change it to be a function:
function SaveMe(myId) {
var str1 = 'UpdateuNationalID ' + myId;
var NationalID = document.getElementById(str1).innerHTML;
// or
var NationalID = document.getElementById(str1).value;
// then
console.log(NationalID);

Related

How to dynamically choose an option from a dynamically populated dropdown

I'm creating a company directory where you can create, read, update and delete entries about employees, departments, and locations. When updating a specific employee, accessed by a button on their employee's row:
You get a modal:
The code for this modal is:
<div class="modal fade" id="update_employee" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header update_header">
<h5 class="modal-title" id="exampleModalLongTitle">Update Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="updatingEmployee_problem" class="alert alert-danger alert-dismissible fade show" role="alert" style="display:none;">
<p id="description_of_update_problem"></p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div id="update_this_id" hidden></div>
<div class="form-group">
<label for="name">First Name</label>
<input class="form-control" id="update_fname">
</div>
<div class="form-group">
<label for="name">Last Name</label>
<input class="form-control" id="update_lname">
</div>
<div class="form-group">
<label for="job_title">Job Title</label>
<input class="form-control" id="update_job_title">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="update_email">
</div>
<div class="form-group">
<label for="department">Department</label>
<div class="row ml-1">
<select data-width="450px" title="Select department" class="selectpicker" id="departmentSearch4" onchange='possibleLocations("#departmentSearch4", "dependentLocation2")'></select>
</div>
</div>
<div class="form-group">
<label for="location">Location</label>
<div class="row ml-1">
<select data-width="450px" title="Select location" id="dependentLocation2" class="selectpicker"></select>
</div>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" onclick="certainDecision('updateTheEmployee')">
<label class="form-check-label" for="flexCheckDefault">
I am happy with the information provided.
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button onclick="updateEmployee()" class="btn btn-primary" id="updateTheEmployee" disabled>Update</button>
</div>
</form>
</div>
</div>
</div>
Departments can have multiple locations. Therefore, my location dropdowns are dynamically populated depending on which department is chosen.
The code for this is:
function possibleLocations(department, id) {
$.ajax({
type: 'POST',
url: 'libs/php/locationOptions.php',
data: {
department: $(department + ' option:selected').text()
},
success: function (result) {
while (document.getElementById(id).firstChild) {
document.getElementById(id).removeChild(document.getElementById(id).lastChild);
}
for (let i = 0; i < result.length; i++) {
var node = document.createElement("OPTION");
var textnode = document.createTextNode(result[i].name);
node.value = result[i].id;
node.appendChild(textnode);
document.getElementById(id).appendChild(node);
}
$('#' + id).selectpicker('refresh');
}
})
}
I fill in this modal, by executing this code when clicking on the row's edit button:
function update_this(ele) {
var row = ele.closest('tr');
var data = row.children;
var id = data[0].childNodes[0].data;
$('#update_this_id').text(id);
document.getElementById('update_fname').setAttribute('value', data[1].childNodes[0].data);
document.getElementById('update_lname').setAttribute('value', data[2].childNodes[0].data);
document.getElementById('update_job_title').setAttribute('value', data[3].childNodes[0].data);
document.getElementById('update_email').setAttribute('value', data[4].childNodes[0].data);
$('#departmentSearch4').val(data[5].childNodes[0].data).trigger('change');
$('#dependentLocation2').selectpicker('val', data[7].childNodes[0].data); << TRYING TO SELECT THE EMPLOYEE LOCATION FROM THE DYNAMIC LOCATION DROPDOWN
$('#update_employee').modal('show');
}
As departments can have multiple locations, I would like to automatically select the employee's location from the dynamic dropdown which is populated from the employee's department so that it looks 'filled out'. Any ideas on how I can achieve this?
I figured out one solution!
I can use a setTimeout so that the dropdown list has time to populate before I select the employee's location. I did it with the following code:
function update_this(ele) {
var row = ele.closest('tr');
var data = row.children;
var id = data[0].childNodes[0].data;
$('#update_this_id').text(id);
document.getElementById('update_fname').setAttribute('value', data[1].childNodes[0].data);
document.getElementById('update_lname').setAttribute('value', data[2].childNodes[0].data);
document.getElementById('update_job_title').setAttribute('value', data[3].childNodes[0].data);
document.getElementById('update_email').setAttribute('value', data[4].childNodes[0].data);
$('#departmentSearch4').val(data[5].childNodes[0].data).trigger('change');
setTimeout(function () { $('#dependentLocation2').selectpicker('val', data[7].childNodes[0].data) }, 1);
$('#update_employee').modal('show');
}
I would still love anyone else's ideas though of how to solve it!

jQuery: Bootstrap Modal not showing

I want to my grant my Admin the priviledges to add and edit user. Clicking the Add button pops up a modal which os userModal and its working perfectly - I send a request to user_action.php (where my PHP and SQL statements are) and it creates a new user.
When the Admin clicks on the Update button, i want the userModal to pop up again, but this time, populated with the username, email and usertype of the user that is to be edited (The modal-title changes from Add User to Edit User and the btn-action changes to 'Edit`). This is not working - the modal doesn't show.
What is the problem?
I have attached the html to my users.php and the jQuery. I have also attached the screenshot of the UI of users.php in case it can be of help.
HTML
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("./database/dbnew.php");
if($_SESSION['usertype'] != 'Admin')
{
header("location:index.php");
}
include("./templates/header.php");
?>
<span id="alert_action"></span>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-6">
<h3 class="panel-title">User List</h3>
</div>
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" align="right">
<button type="button" name="add" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success btn-xs">Add</button>
</div>
</div>
<div class="clear:both"></div>
</div>
<div class="panel-body">
<div class="row"><div class="col-sm-12 table-responsive">
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Email</th>
<th>Name</th>
<th>Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter User Name</label>
<input type="text" name="username" id="username" class="form-control" required />
</div>
<div class="form-group">
<label>Enter User Email</label>
<input type="email" name="email" id="email" class="form-control" required />
</div>
<div class="form-group">
<label>Enter User Password</label>
<input type="password" name="password" id="password" class="form-control" required />
</div>
<div class="form-group">
<label for="usertype">Usertype</label>
<select name="usertype" class="form-control" name="usertype" id="usertype" required>
<option value="">Choose User Type</option>
<option value="Admin">Admin</option>
<option value="Other">Other</option>
</select>
<small id="t_error" class="form-text text-muted"></small>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="id" id="id" />
<input type="hidden" name="btn_action" id="btn_action" />
<input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
jQuery
<script>
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').html("<i class='fa fa-plus'></i> Add User");
$('#action').val("Add");
$('#btn_action').val("Add");
});
var userdataTable = $('#user_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax":{
url:"user_fetch.php",
type:"POST"
},
"columnDefs":[
{
"target":[4,5],
"orderable":false
}
],
"pageLength": 25
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
$('#action').attr('disabled','disabled');
var form_data = $(this).serialize();
$.ajax({
url:"user_action.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#user_form')[0].reset();
$('#userModal').modal('hide');
$('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
$('#action').attr('disabled', false);
userdataTable.ajax.reload();
}
})
});
$(document).on('click', '.update', function(){
var id = $(this).attr("id");//user_id
var btn_action = 'fetch_single';
$.ajax({
url:"user_action.php",
method:"POST",
data:{id:id, btn_action:btn_action},//user_id
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#username').val(data.username);
$('#email').val(data.email);
$('#usertype').val(data.usertype);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit User");
$('#id').val(id);//user_id
$('#action').val('Edit');
$('#btn_action').val('Edit');
$('#password').attr('required', false);
$('#usertype').attr('required', false);
}
})
});
});
</script>
Screenshot
users.php UI
Any form of assistance will be appreciated.

Show a succes/error message if data was/wasn't stored in data base on the same form page

I have a form from where the user imput data to the database and a php file with the function to do so.
I'd like to show an alert message on the same form page using javascript without refresing the page.
I don't know much about JS and I have tried every possible solution I came across but I cannot find the solution yet, what am I doing wrong? I hope someone could help me.
Edit: I decided to use modals to do this but modal is not showing and PHP file gets opened
Edit 2: I got it to show the modal on screen, but It has no message, not even the title specified in the h4 tags
What I'd like the user to see as message is the echo in the PHP file.
this is what I tried:
form code:
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
<div class="col-sm-12 form-group">
</div>
</form>
Modal:
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS function in the form page:
<script type="text/javascript">
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario="EnviarUsuario"; //name
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
url : 'Logica/Usuario.php',
success : function(data){
$("#MSJ").html(data);
$("#ModalMSJ").modal("show");
}
});
return false;
});
</script>
PHP file:
$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];
if(isset($_POST["btnEnviarUsuario"]))
{
$Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($Conexion->connect_error)
{
die("Connection failed: " . $Conexion->connect_error);
}
$sql = "insert into usuario
(NombreRepresentante,NombreComercial,Expediente,Observacion)
values
('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";
if($Conexion->query($sql) === TRUE) {
/*Message I'd like to show to user*/
echo "Usuario guardado exitosamente";
}
Just remove the form tag and it won't fully refresh the page.
Then remove your alert from the php file and put it as shown below
<script>
$(document).ready(function(){
$("#EnviarUsuario").click(function(){
$.ajax({
url: "Logica/Usuario.php",
type: 'post',
data: {"btnEnviarUsuario":document.getElementByName("EnviarUsuario").value},
success: function(result){
//You put here your alert
alert("Usuario guardado exitosamente");
}
});
});
});
</script>
seems you having problem for using bootstrap. I wrap it using jsfiddle and fake JSON API. You could try it. I Hope it help. It's just simple problem that you have there. , your code is wrong on the ajax data.
see this.
https://jsfiddle.net/hp9jzfmo/1/
$(function(){
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario=$('#EnviarUsuario').val();
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize(), // This is the right one
url : 'https://jsonplaceholder.typicode.com/posts',
success : function(data){
$("#MSJ").html(JSON.stringify(data));
$("#ModalMSJ").modal('show');
}
});
return false;
});
});
the body should be
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The PHP Part I think you could do your self, as far as the data passed to server. I hope it helps :)
This is the final solution:
Form Code:
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
<div class="col-sm-12 form-group">
</div>
</form>
Modal Code
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold; color:black;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="color:red;" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS Code:
<script type="text/javascript">
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario="EnviarUsuario"; //variable to check if user clicked the button
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
url : 'Logica/Usuario.php',
success : function(data){
$("#MSJ").html(data);
$("#ModalMSJ").modal("show");
}
});
return false;
});
</script>
PHP File Code:
$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];
if(isset($_POST["btnEnviarUsuario"]))
{
$Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($Conexion->connect_error)
{
die("Connection failed: " . $Conexion->connect_error);
}
$sql = "insert into usuario
(NombreRepresentante,NombreComercial,Expediente,Observacion)
values
('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";
if($Conexion->query($sql) === TRUE) {
/*Message I'd like to show to user*/
echo "Usuario guardado exitosamente";
}

Modal does not close after clicking button

im trying to build a modal, with a try-catch block, so if everyting is valid and entered correctly in the form, the modal should be closed
This is the function login, i wonder why $('#dialog').modal('hide'); does not work
<script>
function login() {
var kontakt = new Kontakt();
kontakt.name = document.getElementById('name').value;
kontakt.email = document.getElementById('email').value;
kontakt.plz = document.getElementById('plz').value;
kontakt.ort = document.getElementById('ort').value;
kontakt.strasse = document.getElementById('strasse').value;
try {
kontakt.pruefe();
}
catch(err) {
return window.alert(err.message);
}
kontakteSpeicher.neuerKontakt(kontakt);}
$('#dialog').modal('hide');
</script>
</head>
This is the modal
<div class="container">
<h2></h2>
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#dialog">
Login-Dialog öffnen
</button>
<!-- The Modal -->
<div class="modal" id="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Login (im header)</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="container">
<p>im body:</p>
<form>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Name" id="name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">E-Mail</label>
<div class="col-sm-10">
<input type="email" class="form-control" placeholder="E-Mail" id="email">
</div>
</div>
<div class="form-group row">
<label for="plz" class="col-sm-2 col-form-label">PLZ</label>
<div class="col-sm-10">
<input type="number" class="form-control" placeholder="PLZ" id="plz">
</div>
</div>
<div class="form-group row">
<label for="ort" class="col-sm-2 col-form-label">Ort</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="ort" placeholder="Ort">
</div>
</div>
<div class="form-group row">
<label for="strasse" class="col-sm-2 col-form-label">Strasse und Hausnummer</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="strasse" placeholder="Strasse und Hausnummer">
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-block" onclick="login()">Speichern</button>
</div>
</div>
</div>
</div>
</div>
The only problem you have is that the $("#dialog").modal('hide') statement isn't inside your login function body.
This should work.
function login() {
var kontakt = new Kontakt();
kontakt.name = document.getElementById('name').value;
kontakt.email = document.getElementById('email').value;
kontakt.plz = document.getElementById('plz').value;
kontakt.ort = document.getElementById('ort').value;
kontakt.strasse = document.getElementById('strasse').value;
try {
kontakt.pruefe();
}
catch(err) {
return window.alert(err.message);
}
kontakteSpeicher.neuerKontakt(kontakt);
$('#dialog').modal('hide');
}
It seems like you are closing your login function on the line before the call to close the modal.
Try to change this:
kontakteSpeicher.neuerKontakt(kontakt);}
$('#dialog').modal('hide');
to this:
kontakteSpeicher.neuerKontakt(kontakt);
$('#dialog').modal('hide'); }

Displaying Javascript response object in MODAL

I have created a view as:
<div class="container" style="padding-top:20px">
<div class="row">
#foreach (var item in Model)
{
<div class="col-lg-4" style="padding-top:20px;">
<div class="card" style="width:18rem">
<img src="#Url.Content(item.ImagePath)" class="card-img-top" />
<div class="card-body">
<div class="row">
<h5 class="card-title">#item.ProductName</h5>
<p style="color:crimson">  ( Rs #item.ProductPrice )</p>
</div>
#*Details*#
<button class="btn btn-primary btndetails" data-product-id="#item.Id" #*data-target="#loginModal" data-toggle="modal"*#>Details</button>
</div>
</div>
</div>
}
</div>
when I click the Details button the JavaScript function is invoked in which I am making an ajax call to Admin controller and GetProduct actionMethod which takes an Id, Gets the data with that id and returns a JSON object:
<script>
$(document).ready(function () {
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
}
});
});
});
</script>
Its all working correct until here, I get the object in success function response object but now I want to display that object in a MODAL that I have created as:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal fade" data-backdrop="static" id="loginModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"> Details</h4>
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
#using (Html.BeginForm())
{
}
</div>
<div class="modal-footer">
<button class="btn btn-success">Save</button>
<button class="btn btn-primary" data-dismiss="modal">Close</button>
<button class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
</div>
So in short I want to display the object I received in JavaScript Response object in MODAL I created.
Wait it looks like you are trying to use ASP.Net rendering engine (which is generated during request on SERVER side) to render a result of an AJAX request which is performed by the client.
Sorry friend but that's just not going to work.
I mean if you really have to use ASP.Net to render that form, I'd suggest creating a separate view which just returns the form (Html.BeginForm()) section, then use jquery to paste that into the modal-body class as a raw html.
$('.modal-body').html(response);
It'd be a really bad solution from a MVC point of view and I'd advise against that, but it'd get the job done.
I am succesful in woring out the solution as :
I used getElementById and value functions to get the MODAL input field and then used value function to set the values in response object to MODAL input fields.
My AJAX Call is :
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
var pName = document.getElementById("pName");
pName.value = response.ProductName;
var pPrice = document.getElementById("pPrice");
pPrice.value = response.ProductPrice;
var pDPrice = document.getElementById("pDPrice");
pDPrice.value = response.DiscountPrice;
var imgTitle = document.getElementById("imgTitle");
imgTitle.value = response.ImageTitle;
var stock = document.getElementById("stock");
stock.value = response.Stock;
var description = document.getElementById("description");
description.value = response.Description;
var img = document.getElementById("img");
img.value = response.ImagePath;
$("#img").attr("src", img);
}
});
});
And the modal i created below it is :
<div class="modal-body">
<form>
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Product Name</label>
<input id="pName" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div>
<img src="" id="img" width="150px" height="150px" style="float:right" />
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Product Price</label>
<input id="pPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Discount Price</label>
<input id="pDPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Image Title</label>
<input id="imgTitle" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Quantity in stock</label>
<input id="stock" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Description</label>
<input id="description" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<div class="col-lg-6">
<label for="exampleInputEmail1">Category</label>
#Html.DropDownList("Category", new SelectList((System.Collections.IEnumerable)ViewData["Category"], "Id", "CategoryName"), new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
</form>
</div>
Anfinal outpur is like :

Categories