What I am trying to do: Display a value entered into a form in the modal that is shown by submitting the form.
What I tried first: To simply reference the "id" element in the modal. Realized this probably would not work because the modal is generated during page load and before the form has any values. So the value will be empty.
What I am currently trying: To return the form value after submission from my controller. Use boostrap Table('load', data) to load the table after form return and display in the modal.
I am very new to Java and feel like I may be making this a lot more complicated than it needs to be. Here is the current code:
If any additional code snippets needed, let me know...
javascript - I know I am making it into submit.done because the table is displaying, just no data.
$table = $("#notesTable").bootstrapTable({
data: []
});
$("#notesTable").hide();
$("#btnSubmit").click(function() {
var dataString = $("#extractForm").serialize();
var submit = $.ajax({
url: "${pageContext.request.contextPath}/doc/validateAuditId",
type: "POST",
cache: false,
data: dataString
});
submit.done(function(data) {
if (data.length && data.length > 0) {
$("#notesTable").show();
$("#notesTable").bootstrapTable('load', data);
$("#dlgUpload").modal('show');
}else{
$("#notesTable").hide();
$("#dlgUpload").modal('show');
}
});
Return from controller
Modal:
<html>
<body>
<div id="dlgUpload" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="noteTitle">Upload File</h4>
</div>
<div class="modal-body">
<div class="tabs-div">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Upload Document</li>
<li role="presentation">Select Doc Type</li>
<li role="presentation">Perceptive Content</li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active" id="tabUploadDoc">
<br>
<form:form method="POST" action="${pageContext.request.contextPath}/doc/uploadFile" enctype="multipart/form-data">
<div class="row">
<div class="col-xs-3 form-group">
<form:label path="fileName">Select a file to upload:</form:label>
</div>
<div class="col-xs-2 form-group">
<input type="file" name="fileName" />
</div>
</div>
<table id="notesTable" data-classes="table table-striped table-no-bordered" data-undefined-text="" data-toggle="table">
<thead>
<tr>
<th data-field="retAuditId" data-visible="true" data-align="left" data-sortable="false">Audit ID</th>
</tr>
</th>
Output: Nada
Need to return a list from the controller. Was returning a String.
Related
I am developing a feature that needs the Ajax request. First I open a modal by clicking a button that has the class '.open-email-modal'. And after that, it opens a modal where it has 2 fields to enter values for a register, and below it has a table. When opening the modal the first time, everything happens normally, the register with the call of the request Ajax goes through a controller and returns in response to the value registered with its respective token. Below are the codes I developed. (I'm using Laravel).
This is the modal code.
<div class="col-md-4">
<div class="modal fade" id="emailModal" tabindex="-1" role="dialog" aria-labelledby="modal-form" aria-hidden="true">
<div class="modal-dialog modal- modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-body p-0">
<div class="card bg-secondary shadow border-0">
<div class="card-header bg-transparent pb-4">
<div class="text-muted text-center mt-2 mb-3 text-uppercase"><h1>Adicionar Email</h1></div>
<div class="text-center text-muted mb-4">
<small> Preencha os campos dos emails </small>
</div>
</div>
<div class="card-body px-lg-5 py-lg-5">
<form id="emailModalProspect" method="post" action="{{ route('prospectEmails.store') }}">
#csrf
{{ method_field('post') }}
<input hidden name="prospect_id" id="prospect_id_email" type="text">
<div class="form-group mb-3">
<label class="form-control-label" for="prospect-email-name">{{ __('Nome') }}</label>
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input class="form-control" id="prospect-email-name" name="name" placeholder="Digite o nome do proprietário do email" type="text" required>
</div>
</div>
<div class="form-group mb-3">
<label class="form-control-label" for="prospect-email-email">{{ __('Email') }}</label>
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-email-83"></i></span>
</div>
<input class="form-control" id="prospect-email-email" name="email" placeholder="Digite o email da empresa/cliente" type="email">
</div>
</div>
<div class="text-center">
<button type="submit" id="save-email" class="btn btn-primary my-4 store-email text-uppercase">Cadastrar email</button>
</div>
</form>
<div class="table-responsive ">
<table class="table align-items-center table-flush tablesorter-dropbox text-center" id="prospect-email-table">
<thead class="thead-light text-center" >
<tr class="text-center">
<th scope="col" class="text-center col-sm-2"><b>{{ __('Nome') }}</b></th>
<th scope="col" class="text-center col-sm-2"><b>{{ __('Email') }}</b></th>
<th scope="col" class="text-center col-sm-2"><b>{{ __('Opção') }}</b></th>
</tr>
</thead>
<tbody class="text-center" id="received-emails">
</tbody>
</table>
</div>
<div class="text-center">
<button type="button" class="btn btn-default my-4 text-uppercase" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is the code in JQuery where it calls the Ajax request.
$('.open-email-modal').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
let p = JSON.parse($(this).attr('data-entity'));
let modal = $('#emailModal');
let form = $('#emailModalProspect');
$('#prospect_id_email').val(p.id).change();
$('.store-email').on('click', function(b){
b.stopPropagation();
b.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
let url = '{{route("prospectEmails.store")}}';
$.ajax({
url: url,
type: "POST",
data : form.serialize(),
async: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: "json",
success:function(response) {
console.log(response);
showEmails(p.id);
}
});
});
if(p.id){
showEmails(p.id);
}
modal.modal({show : true});
});
This is my controller code.
public function store(Request $request){
ProspectEmails::create(array_merge($request->all(), ['company_id' => Auth::User()->company_id], ['prospect_id'=>$request->prospect_id], ['tag'=>false]));
return Response()->json($request);
}
The problem is this, as soon as I open for the first time and register, everything works normally. But when I close the modal and open again and register, it is returned that register that I made 2x without any token. Close the modal again and open again and register, and return that register 3x, without any token again. showEmails is a function that shows the registration in the table normally and also shows the repeated values every time that registration. Even the database shows the repeated values, so I have confirmation that the main error is either in my modal or in the Ajax request with the POST method. Can someone give me a hand?
You are registering click each time you open the modal:
$('.store-email').on('click', ...
The first time you open it, you register a listener.
The second time you open it, you register a listener, and now you have 2, and so on.
Since you don't reload the page, the listeners do not go away. You should be removing your event listener when the modal closes or checking to see if you have added it already and not adding it again:
https://api.jquery.com/off/
An easy way to do it would be to call the off method right before registering the listener, guaranteeing you only have 1 listener attached:
let modal = $('#emailModal');
let form = $('#emailModalProspect');
$('#prospect_id_email').val(p.id).change();
// ADDED LINE
$('.store-email').off('click');
$('.store-email').on('click', function(b){
I am having trouble displaying information on my popup page. I created main view where the user clicks a card and it should trigger a modal to display required information (including partial view) through ajax, however that partial page should be displayed through a controller but the action result within a controller is not triggered at all despite the fact that I have specified the data-url withing my java-script function.
Here is my index page:
<div id="pageContainer">
<div class="container">
<!--Boxers Cards-->
<div class="row text-center default-div-top-padding">
<div class="col-lg-3 col-md-6 mb-4 rounded fighter-card" id="FighterDetails">
<a id="popup-button" data-url="#Url.Action("FighterDetails", "RankingsController")" data-toggle="modal" data-target=".fighter-modal">
<img class="card-img-top" src="http://nyfights.com/wp-content/uploads/2017/12/Screen-Shot-2017-12-11-at-5.10.25-PM.png" alt="" />
<div class="card-body fighter-card-body-color" style="border-bottom: 2px solid rgb(255, 172, 0)">
<div class="card-title fighter-card-title">Vasyl Lomachenko</div>
<ul class="fighter-card-information">
<li>
<div class="fighter-card-information-title">Belts: </div>
<div class="fighter-card-information">WBA, WBO, IBF, WBC</div>
</li>
<li>
<div class="fighter-card-information-title">Record:</div>
<div class="fighter-card-information">11-1-0 9KO</div>
</li>
</ul>
</div>
<div class="card-footer fighter-card-ranking-position fighter-card-footer-color">
<h1>1</h1>
</div>
<input type="hidden" name="popup=title" value="Fighter Details" />
</a>
</div>
</div>
<!--Boxers Cards End-->
</div>
</div>
<!--Modal-->
<div class="modal fade fighter-modal" role="dialog" aria-labelledby="gridSystemModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header blueBackground goldBorderBottom">
<button type="button" class="close" data-dismiss="modal" aria-label="close" data-toggle="tooltip" data-placement="left" title="close">
<span aria-hidden="true">
×
</span>
</button>
<span class="modal-title" id="gridSystemModalLabel"></span><br />
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="">
<div id="ajax-target-container"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
//AJAX Popup Control - Renders a popup with designed partial view
$("container").on("click", "#popup-button", function () {
//Set the URL
var url = $(this).attr('data-url');
//Set the title
var popupTitle = $(this).find($('input[name=popup-title]')).val();
$(".modal-title").text(popupTitle);
//Set a default spinner
$(".modal #ajax-target-container").append("<span class='blueText'><i class='fa fa-spinner fa-spin fa-3x fifteenPxSpacingRight'></i> Loading... </span>");
$.ajax({
type: "GET",
cache: false,
url: url,
success: function (data) {
$(".modal #ajax-target-container").empty();
$(".modal #ajax-target-container").html(data);
}
})
});
});
</script>
My Partial View:
<div class="row">
#using (Html.BeginForm("", "", FormMethod.Post, new { #id = "Fighter-Details" }))
{
#Html.AntiForgeryToken()
<div class="card-body fighter-card-body-color" style="border-bottom: 2px solid rgb(255, 172, 0)">
<div class="card-title fighter-card-title">Vasyl Lomachenko</div>
<ul class="fighter-card-information">
<li>
<div class="fighter-card-information-title">Belts: </div>
<div class="fighter-card-information">WBA, WBO, IBF, WBC</div>
</li>
<li>
<div class="fighter-card-information-title">Record:</div>
<div class="fighter-card-information">11-1-0 9KO</div>
</li>
</ul>
</div>
}
And my controller:
[HttpGet]
public PartialViewResult FighterDetails()
{
return PartialView("~/Views/Rankings/PartialViews/FighterDetails.cshtml");
}
Now when I click the card it will display only the top of the popup:
And that's it. Controller is not triggered at all so it's seems it is not going through the java script function but I'm not sure why.
Any help would be appreciated,
Thanks
In your JS code, it looks like you're missing the '.' before 'container' in the jQuery selector. Since 'container' is a class attribute, the proper jQuery selector is '.container'.
Try changing
$("container").on("click", "#popup-button", function () {
to
$(".container").on("click", "#popup-button", function () {
I've been looking at examples and nothing seems to work. Right now I have a button group, where each button serves as a separate category. Once the button is clicked, it will show an accordion and within the accordion there will be forms. For testing purposes, I only have one form right now.
The problem I'm running into is that once I click the submit button, the page completely reloads and once the page is returned everything is closed. I've tried using updatePanel and have had zero luck.
Basically, I want everything to remain open after the reload that was open before the reload.
<asp:ScriptManager id="script1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel id="panel1" runat="server">
<div class="btn-group-vertical" style="width:100%; ">
#* Bucket Group 1 *#
<div class="btn-group">
<button type="button" class="btn btn-primary" id="formButton1" style="background-color:#EEEEEE; border-color:darkgrey; color:black;"><p>Bucket </p> <text style="font-size:80%;"> Bucket1</text></button>
#* Overall form for Monitoring *#
<form asp-controller="test" method="post" role="form" onsubmit="return confirm('Do you really want to carry out this action?');" id="form1" style="display:none;">
<div id="accordion" role="tablist" aria-multiselectable="true">
#* Form 1 *#
<div class="card">
<div class="card-header" role="tab" id="headingTwo">
<h5 class="mb-0">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" style="font-size:15px;">
Test1
</a>
</h5>
</div>
<div id="collapseTwo" class="collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="card-block">
<div class="form-group">
<div class="form-group">
<p> This script will return a value.</p>
</div>
#Html.DropDownList("Envs", new SelectList(Enum.GetValues(typeof(Envs))), "Select Enivronment", new { #class = "form-control" })
<br>
<div>
<button type="submit">Submit</button>
</div>
<br />
#* Space to display output *#
<h5>Output: </h5>
<div>
<textarea cols="20" rows="2" class="form-control" style="color:cadetblue;font-weight:bold;"> #ViewBag.serviceResponse </textarea>
</div>
</div>
</div>
</div>
</div>
#* Form 2 *#
</div>
</form>
</div>
#* Bucket Group 2 *#
<div class="btn-group">
<button type="button" class="btn btn-primary" id="formButton2" style="background-color:#EEEEEE; border-color:darkgrey; color:black;"><p>Test2</p> <text style="font-size:80%">Test 2</text></button>
<form id="form2" method="post" style="display:none;">
<div id="accordion" role="tablist" aria-multiselectable="true">
<div class="card" id="get">
<div class="card-header" role="tab" id="heading">
<h5 class="mb-0">
<p> Test2.</p>
</h5>
</div>
</div>
</div>
</form>
</div>
</div>
</asp:UpdatePanel>
Javascript functions to open when buttons are clicked.
$("#formButton1").click(function () {
$("#form1").toggle();
});
// Write your JavaScript code.
// Write your Javascript code.
$("#formButton2").click(function () {
$("#form2").toggle();
});
You have two options:
Don't reload the page (add a click handler to submit form data without using the built-in HTML submit)
Use local storage to store the state of which accordion section was open and initializing the page with the same section open
My Question:
I have a main page some fields when user click save button using Ajax.BeginForm i'm saving the details this is working successsfuly.
Inside main form there is one button(task) when user click that button partial window will open then they will fill some details. when partial window save button clicking automatically main page save action method is calling...first it save partial save details then immediately its saving main page details also then i'm getting two time saved successfully message.
when main page save button click only it should save main page fields. when partial page save button click it should save partial page fields only(partial page save i'm using jquery.
Main Page:
#using (Ajax.BeginForm("savePhase", "Search", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "ChmHeaderPage",OnSuccess= "OnSuccessMain" }, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.ChangeRequestList.FirstOrDefault().changeId);
#Html.HiddenFor(model => model.ChangeRequestList.FirstOrDefault().Phase);
<div class="col-md-offset-0 panel-body">
<div class="form-group">
#Html.LabelFor(model => model.Importance, htmlAttributes: new { #class = "col-md-3 control-label" })
<div class="col-md-3">
#Html.DropDownListFor(model => model.ImportanceVal, new SelectList(Model.Importance, "OptionId", "OptionName", Model.ImportanceVal), new { #class = "form-control", #Title = "Message Need to be Show" })
</div>
#Html.LabelFor(model => model.Urgency, htmlAttributes: new { #class = "col-md-2 control-label" })
<div class="col-md-3">
#Html.DropDownListFor(model => model.UrgencyVal, new SelectList(Model.Urgency, "OptionId", "OptionName", Model.UrgencyVal), new { #class = "form-control", #Title = "Message Need to be Show" })
</div>
</div>
<div class="col-md-12 ">
#Html.Label("Enter Task*")
<button type="button" id="Analysisbtn" class="btn btn-link " data-toggle="modal" data-target="#myModal">Select Task</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-open strech-modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Analysis</h4>
</div>
<div class="modal-body">
#Html.Partial("_TaskPage")
</div>
</div>
</div>
</div>
</div>
<!-- Form actions -->
<div class="row panel-body">
<div class="col-md-12 text-center">
<button type="submit" name="buttonValue" class="btn btn-danger" value="Close">Save & Close</button>
<button type="submit" name="buttonValue" class="btn btn-primary" value="Save">Save</button>
</div>
</div>
</div>
}
Partial Page:
#model www.ChangeManagementTool.ViewModels.SearchViewModel
<div class="panel-group" id="accordion" role="tablist" aria-
multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="more-less glyphicon glyphicon-plus"></i>
Task
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse first" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<div class="table-responsive center-block" data-tab-content="#item.Key" style="display:#displayText">
<table class="table table-responsive sena" id=#item.Key>
<tr>
<th>Department</th>
<th>Plant</th>
<th>Country</th>
<th>Responsibles</th>
<th>DueDate</th>
</tr>
<tbody>
#foreach (var analysisTask in item.Value)
{
<tr>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="form-group">
<div class="col-md-12 text-center">
<button type="submit" id="btnSaveReal" class="btn btn-primary ">Save Task </button>
</div>
</div>
}
</div>
</div>
</div>
jquery Save Coding
<script type="text/javascript">
$('#btnSaveReal').click(function (e) {
var listex = [];
debugger;
$('#RealTask tbody tr').each(function (index, ele) {
var saveItem2 = {
ChangeId: $('#ChangeIdR').val(),
PlantId: $('#PlantIdR' + index).val(),
DepartmentId: $('#DepartmentIdR' + index).val(),
MstTaskId: $('#MstTaskIdR' + index).val(),
AffectedItemId: $('#AffectedItemIdR' + index).is(":checked")
}
listex.push(saveItem2);
})
//Save Coding
var url = applicationRoot + '/Search/SaveRealizationTaskdetails';
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({ 'objmodelRel': listex, actionR: 'AnalyzeRealize' }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (Data) {
if (Data.status) {
alert(Data.responseText);
} else {
alert(Data.responseText);
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
function toggleIcon(e) {
$(e.target)
.prev('.panel-heading')
.find(".more-less")
.toggleClass('glyphicon-plus glyphicon-minus');
}
$('.panel-group').on('hidden.bs.collapse', toggleIcon);
$('.panel-group').on('shown.bs.collapse', toggleIcon);
Controller Code:
public ActionResult savePhase(SearchViewModel objmodel, string buttonValue)
{
save code---------------
return RedirectToAction("FetchChgReqDetails");
}
public JsonResult SaveRealizationTaskdetails(List<ChangeRequestRealizationTask> objmodelRel, string actionR)
{
--save code
return new JsonResult { Data = new { status = true, responseText = "Successfuly saved!" }, JsonRequestBehavior= JsonRequestBehavior.AllowGet };
}
As per your questions i will suggest you to try below this if it helpful to you.
First change Partial view button type="button" instead of type="submit"
and on main form submit send all data including Partial view data using AJAX
I have a page where a generate buttons that have data-id in them. When i click on the button a send the data-id through ajax to my php code, open modal window and generate content with recieved id. But the problem is that i need to refresh the page first to even get some value inside $_POST variable, and after i open and close my modal, i need to refresh page again so my variables update and doesnt open same window.
$(document).ready(function(){
// Otevre modal
$('.show-modal').click(function(){
var product_id = $(this).attr('data-id');
$.ajax({
type: 'POST',
cache: false,
data: {modalID : product_id},
url: 'includes/getID.php', // tomuto souboru predas idecko produktu, zapises do kosiku atd.
success: function(data) {
$("#itemBox").modal('show');
// treba nejaka hlaska, ze byl pridan do kosiku
}
});
// kod co otevre modal, mkrni na bootstrap manual jak je otevira nebo si otevreni nadefinuj sa
//$('.product_id').val(productID);
});
});
Here is JS code,
<?php
if(!isset($_SESSION)){
session_start();
}
if(isset($_REQUEST['modalID'])){
$_SESSION['modalBoxID'] = $_REQUEST['modalID'];
}
?>
Here is how i am saving the requested ID from ajax.
and here is how i generate my modal boxes, the problem is that without refreshing page, every box that i open have same content in it.
<?php
if(!isset($_SESSION)){
session_start();
}
if(!isset($_SESSION['sessName'])){
$_SESSION['sessName'] = 'visitor';
}
if(!empty($_SESSION['modalBoxID'])){
$sql = "SELECT * FROM vehicle WHERE vehicle.id='{$_SESSION['modalBoxID']}'";
$sqlquery = $db->query($sql);
$_SESSION['modalBoxID'] = NULL;
}
?>
<div class="container">
<!-- Modal -->
<div class="modal fade" id="itemBox" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body display-content">
<div class="container-fluid">
<?php while($details = mysqli_fetch_assoc($sqlquery)) : ?>
<div class="col-md-4"><img src=<?php echo $details['image'];?> class="image-responsive">
<div class="col-sm-6">
<form action="add_cart.php" method="post">
<div class="form-group">
<label for="quantity">Quantity:</label>
<input type="text" class="form-control" id="quantity" name="quantity">
</div>
</form>
</div>
<div class="col-sm-6">
<br/>
<button type="button" class="add-to-basket btn btn-success" >ADD TO CART</button>
</div>
</div>
<div class="col-md-1"></div>
<div class="col-md-7" id="desc">
<p><b>Model:</b> <?php echo $details['model'];?></p>
<p><b>Engine:</b> <?php echo $details['engine'];?></p>
<h4>Description</h4>
<p><?php echo $details['description'];?></p>
<hr>
<hr>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
Is this even possible with solution that i have ? I dont even get any content on first page load, i need to refresh it so my ID saves to variable and then it will show some content.
Add below to your javascript. It removes the previous data from modal body. You might experience few some delay before the new content is loaded.
$(document.body).on('hidden.bs.modal', function () {
$("#itemBox").removeData('bs.modal');
});