Displaying Javascript response object in MODAL - javascript

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 :

Related

Get Textbox value from bootstrap modal dynamically

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);

How to delete div and all element inside div? Javascript, html, css

I have a function that clears the entire div and it disappears but still appears in the inspect (html). This is a real problem because we have this input type field on the email and I got this empty data in email. I only want when this value is not chosen to completely remove me from html and inspect. Look at my code and try to catch the error. The most important things in the whole code that you need to pay attention are onchange="checkSelected()" in html and first script tag which manipulate with that. It should simply become a display none but it still stands there.
<div class="modal fade" id="montageModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content" style="display: flex;">
<div class="modal-body">
<form id="schedule_form" class="clearfix" action="index.php?route=api/reifenmontage" method="post">
<div class="container-fluid">
<div class="step_1" >
<h3 class="modal-title">Reifenmontage Termin buchen </h3>
<div class="row termin_row">
<div class="col-xs-12 col-sm-4">
<div class="row">
<label>Pneu-Typ</label>
</div>
</div>
<div class="col-xs-12 col-sm-6">
<div class="row">
<select onchange="checkSelected()" class="form-control" name="pneu" id="pneu">
<option value="Motorrad">Motorrad</option>
<option value="Auto">Auto</option>
</select>
</div>
</div>
</div>
<div id="additionalRow" class="row termin_row" >
<div id="reifenmontage-input" class="row termin_row">
<div class="col-xs-12 col-sm-4">
<div class="row">
<label>Mark und model</label>
</div>
</div>
<div class="col-xs-12 col-sm-4">
<div class="row">
<select name="marka" class="form-control" id="button-getdata">
</select>
</div>
</div>
<div class="col-xs-12 col-sm-4">
<div class="row">
<select name="model" class="form-control" id="result" >
</select>
</div>
</div>
</div>
</div>
<div class="row termin_row">
<div class="col-sm-4 col-xs-12">
<div class="row"><label>2. Terminvorschlag</label></div>
</div>
<div class="col-sm-4 col-xs-6">
<div class="row">
<div class="input-group date" id="date-2" data-termin="1">
<input type='text' class="form-control" name="date[1]" />
<span class="input-group-addon">um</span>
</div>
</div>
</div>
<div class="col-sm-4 col-xs-6">
<div class="row">
<div class="input-group time" id="time-2" data-termin="1">
<input type='text' class="form-control" name="time[1]" />
<span class="input-group-addon">Uhr</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="checkbox">
<label>
<input type="checkbox" name="accept" id="accept"> Ich akzeptiere die Teilnahmebedingungen
</label>
</div>
</div>
<div class="row text-center">
<button type="button" class="btn btn-primary btn-lg btn-submit" id="next_step" disabled="disabled">Anfrage senden</button>
</div>
</div>
<div class="step_2">
<h3 class="modal-title">Your contact info</h3>
<div class="">
<div class="form-group clearfix">
<input type="text" name="name" value="<?= $user['name'] ?>" placeholder="Name and Lastname" class="form-control name text" required />
</div>
<div class="form-group clearfix">
<input type="text" name="phone" value="<?= $user['phone'] ?>" placeholder="Phone" class="form-control phone text" required />
</div>
<div class="form-group clearfix">
<input type="email" name="email" value="<?= $user['email'] ?>" placeholder="Email" class="form-control email text" required />
</div>
<div class="text-center">
<button type="submit" id="submit" class="btn btn-default btn-lg btn-submit" >Suchen</button>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">SCHLIESSEN</button>
</div>
</div>
</div>
</div>
and my script tag
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
let additionalRow = document.getElementById('additionalRow');
function checkSelected() {
if (selectItem.selectedIndex == "1") {
additionalRow.style.display = 'none';
} else {
additionalRow.style.display = 'block';
}
}
</script>
<script type="text/javascript">
$('#button-getdata').on('change', function() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
},
success: function(json) {
if (json['success']) {
$("#result").empty();
for (i in json['success']) {
var element = json['success'][i];
var o = new Option(element['model'], element['model']);
$("#result").append(o);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$("#result").append(o);
}
// document.getElementById("schedule_form").reset();
}
}
});
});
</script>
<script type="text/javascript">
$.ajax({
url: 'index.php?route=api/reifenmontage/mark',
context: document.body,
success: function(data) {
const selectControl = $('#button-getdata');
selectControl.html(data.map(ExtractData).join(''));
}
});
function ExtractData(item) {
return ` <option value="${item.value}">${item.label}</option>`;
}
</script>
Try variant with detaching/attaching DOM elements
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
//let additionalRow = document.getElementById('additionalRow');
let detached = '';
function checkSelected() {
if (selectItem.selectedIndex == "1") {
detached = $('#reifenmontage-input').detach();
} else {
detached.appendTo('#additionalRow');
}
}
</script>

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'); }

The angular controller shows the modal form is valid, when it's not

I have a form that's pops in a modal directive (bootstrap UI).
I have 2 input with html5 validation: "required".
In the controller I wanted to find out if the form is valid, then proceed to the server. After I ran into a problem with scopes (when I tried to reffer $scope.FormName.$valid), I found a solution by sending form name with the ng-click.
Then I saw that the controller code shows that the form is valid (even when the required field is empty).
How can I implement check if the form is valid before submitting it.
Here is my code:
form in html
<form name="EmailForm">
<div class="row">
<div class="col-md-1 lbl_hdr">
date:
</div>
<div class="col-md-1">
{{Curr_Date | date:'dd/MM/yyyy'}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1 lbl_hdr">
from:
</div>
<div class="col-md-1">
<input type="email" required placeholder="email" />
<br />
<br />
</div>
</div>
<div class="row">
<div class="col-md-3 lbl_hdr">
message:
</div>
</div>
<div class="row">
<div class="col-md-1">
<textarea class="msg_text" required rows="5"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-9">
<button type="submit" ng-click="SendEmail(EmailForm)" class="btn btn-primary btn_padded_top">send</button>
<button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
</div>
</div>
</div>
</div>
</form>
controller
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: '/js/app/templates/msg_modal.html',
controller: function ($scope) {
$scope.Curr_Date = new Date();
$scope.SendEmail = function (EmailForm) {
if (EmailForm.$valid) {
EmailService.sendEmail("sdsd").success(
function (data) {
});
}//if valid
};
},
size: size
});
};
"if (EmailForm.$valid)" = always true
I had the same problem and turns out that the form elements must have ng-model in order for the AngularJS validation to kick in.
So just add it to all elements and it should be all good, e.g.
<input type="email" required placeholder="email" ng-model="email" />
Try using ng-submit and sending EmailForm.$valid in the arguments.
<form name="EmailForm" ng-submit="SendEmail(EmailForm.$valid)">
<div class="row">
<div class="col-md-1 lbl_hdr">
date:
</div>
<div class="col-md-1">
{{Curr_Date | date:'dd/MM/yyyy'}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1 lbl_hdr">
from:
</div>
<div class="col-md-1">
<input type="email" required placeholder="email" />
<br />
<br />
</div>
</div>
<div class="row">
<div class="col-md-3 lbl_hdr">
message:
</div>
</div>
<div class="row">
<div class="col-md-1">
<textarea class="msg_text" required rows="5"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-9">
<button type="submit" class="btn btn-primary btn_padded_top">send</button>
<button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
</div>
</div>
</div>
</div>
</form>
Then:
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: '/js/app/templates/msg_modal.html',
controller: function ($scope) {
$scope.Curr_Date = new Date();
$scope.SendEmail = function (isValid) {
if (isValid) {
EmailService.sendEmail("sdsd").success(
function (data) {
});
}//if valid
};
},
size: size
});
};

Categories