Modal does not close after clicking button - javascript

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

Related

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";
}

Show Signup modal window then Login modal right away

I have a nav bar with options for signup or login. Once clicked on either it will display a modal window using Bootstrap. What I am trying to do is that when the user is finished with the join modal window (pressed submit button and submitted data to the controller), I want to show the signin modal window right after. Show my idea was when submitting the form data to the controller. The controller would respond back with a display-type equaling "join, signin, nothing" and reinclude the page. In the page it will check what the display-type is then will call either show_join_modal() function if the display-type is signup or call either show_signin_modal() function if the display-type is login.
My idea using JQuery was something like this, Here is code in the startpage.php
<script>
<?php
if (isset($display_type))
if ($display_type == 'signin')
echo 'show_signin_modal();';
else if ($display_type == 'join')
echo 'show_join_modal();';
else
;
?>
function show_signin_modal() {
$("#signinModal").modal("show");
}
function show_join_modal() {
$("#joinModal").modal("show");
}
function hide_all_modal() {
$("#joinModal").modal("hide");
$("#signinModal").modal("hide");
}
</script>
<div class="container">
<div class="modal fade" id="joinModal" role="dialog">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-body">
<form class="form-horizontal" method="post" action="controller.php">
<input type='hidden' name='page' value='StartPage'></input>
<input type='hidden' name='command' value='Join'></input>
<h1>Register</h1>
<div class="form-group">
<label class="control-label col-sm-2" for="username"> Username</label>
<div class="col-sm-10">
<input type="text" name="username" placeholder="Enter username.." required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="password" required> Password</label>
<div class="col-sm-10">
<input name="password" type="password" placeholder="Enter password..">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email" required> Email</label>
<div class="col-sm-10">
<input type="email" name="email" placeholder="Enter email..">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
<button type="cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="modal fade" id="signinModal" role="dialog">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-body">
<form class="form-horizontal" method="post" action="controller.php">
<input type='hidden' name='page' value='StartPage'></input>
<input type='hidden' name='command' value='SignIn'></input>
<h1>Login</h1>
<div class="form-group">
<label class="control-label col-sm-2" for="username"> Username</label>
<div class="col-sm-10">
<input type="text" name="username" placeholder="Enter username.." required>
<?php if (!empty($error_msg_username)) echo $error_msg_username; ?>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="password"> Password</label>
<div class="col-sm-10">
<input name="password" type="text" placeholder="Enter password.." required>
<?php if (!empty($error_msg_username)) echo $error_msg_username; ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
<button type="cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
However, I could not get it to work.
Any ideas. Any sample code? Thanks in advance!
Replace this code with the current on your controller.
<script>
function show_login_modal() {
$("#loginModal").modal("show");
}
function show_signup_modal() {
$("#signupModal").modal("show");
}
function hide_all_modal() {
$("#signupModal").modal("hide");
$("#loginModal").modal("hide");
}
</script>
<?php
if (isset($display_type))
if ($display_type == 'signin')
echo '<script type="text/javascript">show_signin_modal();</script>';
else if ($display_type == 'join')
echo '<script type="text/javascript">show_join_modal();</script>';
//echo 'show_join_modal();';
else
;
?>
I found out how to do it with help from "https://codepen.io/elmahdim/details/azVNbN" which he posted on "Bootstrap modal: close current, open new" under username "Mahmoud". So in order to go from the joinModal window to the signinModal window right after the user submits the form on the joinModal window. I updated the submit button in the joinModal window with:
<button type="submit" class="btn btn-default" data-toggle="modal" data-target="#signinModal" data-dismiss="modal">Submit</button>

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 :

Passing content from <textarea> to api controller

I'm trying to pass content from a form (in a modal) to an api_controller. But I can't get the text out of my <textarea>... even with a simple alert
//Simple HTML-BOOTSTRAP form
<div class="modal-dialog modal65resp">
<div class="modal-content">
<!-- modal-header -->
<div class="modal-header">
<h4>New File</h4>
</div>
<!-- modal-body -->
<div class="modal-body">
<form id="newfileform" class="form-horizontal">
<!-- filename -->
<div class="form-group">
<label for="filename" class="col-sm-2 control-label">FileName:</label>
<div class="col-sm-10">
<input name="filename" type="text" class="form-control" id="filename" placeholder="FileName">
</div>
</div>
<!-- TxtArea -->
<div class="form-group">
<label for="txtarea1" class="col-sm-2 control-label">Text:</label>
<div class="col-sm-10">
<textarea type="text" name="txtarea1" id="txtarea1"></textarea>
</div>
</div>
<!-- apath -->
<div class="form-group">
<label for="apath" class="col-sm-2 control-label">Absolute Path:</label>
<div class="col-sm-10">
<input name="savepath" type="text" class="form-control" id="savepath" placeholder="Absolute Path" readonly>
</div>
</div>
</form>
</div>
<!-- modal-footer -->
<div class="modal-footer">
<div class="pull-left">
<div id="info"></div>
</div>
<div class="pull-right">
<a class="btn btn-default " data-dismiss="modal">Cancel</a>
<a class="btn btn-success " onclick="SaveFile()">Save File</a>
</div>
</div>
</div>
</div>
And this is the script I'm trying to get working an a textarea, with CKEditor in use.
//script
<script>
CKEDITOR.replace('txtarea1');
</script>
<script>
function SaveFile()
{
var path = $('#savepath').val()
var filename = $('#filename').val()
var content = $('#txtarea1').val()
alert(content);
}
</script>
You can access your CKEDITOR instance using CKEDITOR.instances.txtarea1 and get the HTML using getData:
CKEDITOR.instances.txtarea1.getData();

Categories