TwitterBootstrapMvc (3rd): modal dialog state - javascript

I use Modal dialogs to submit new records (Asp.Net, MVC).
<div id="modal-dlg" class="modal fade" tabindex="-1"></div>
<div id="banner-add">
<a class="btn-default btn" data-toggle="modal" href="#Url.Action("BannerSlideNewModal", "Account", new { Model.Id })" data-target="#modal-dlg" target="profile-banner">Add</a>
</div>
On form submit, after data processing, I hide current dialog:
form.submit(function() {
button.attr('disabled', true).text('Please wait ...');
// call service to update/add record
if ($(this).valid()) {
$(this).ajaxSubmit(
{
success: function(data) {
.....
$('#' + context.id).modal('hide');
}
});
});
The problem is, when I open modal dialog again, I want to see blank fields for new entry, but all fields are assigned from previous entry. How I can initialize each time new modal dialog instead of reusing same one?
Thanks.

Just reset your form with reset():
form.submit(function() {
button.attr('disabled', true).text('Please wait ...');
// call service to update/add record
if ($(this).valid()) {
$(this).ajaxSubmit(
{
success: function(data) {
.....
$('#' + context.id).modal('hide');
form.reset();
}
});
});

Related

Hide a card after confirming in bootstrap modal on AJAX success

My delete page contains multiple post with delete button, when delete button is pressed bootstrap bootstrap modal opens and will ask for confirmation are you sure you want to delete post ? YES : NO
when YES button is pressed .click(function (e){....} sends AJAX request to database, if ajax return success that paticular card should be hidden
so i tried with following code
$(document).ready(function () {
$("#confirm").click(function (e) {
e.preventDefault();
var that = this;
const act = $(this).attr('data-act');
const para = $(this).attr('data-para');
const hash = $(this).attr('data-hash');
$.ajax({
url: '/include/ajax/mark_sold.php', // Call delete.php to update the database
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
$(that).closest('div.card').hide(); //to hide div after ajax success
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
return false;
});
HTML
<div class="card border-0 small col-lg-3 col-md-2 col-6 mb-2 px-1">
<img class="card-img-top rounded-0" src="/upload/" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">title</h6>
</div>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-sm modalopen" data-hash="6d8ce77d206011027297b693be999704" data-para="A4IxzuRP8ATv">delete</button>
</div>
How do i hide card after confirming in modal
The problem in your code is, that your variable "that" is not referring to the delete button, but to the confirm button of the dialog, therefore you can't use closest() function. At this point, you should use some specific identification for your card/delete button. For example:
$('button[data-hash="'+hash+'"]') .closest('div.card').hide();
Another point that I don't see in your code is the transfer of data variables (act, para, hash) to the dialog confirm button. For example your code $(this).attr('data-hash') can't reach value from the delete button because $(this) refers to the dialog confirm button. The solution to this problem is to pass a unique identifier to the dialog button.
$(".deleteBtn").on('click',function(){ //Add on click event to all delete buttons
$("#confirm").data("hash",$(this).data("hash")); //Pass hash value to dialog confirm button
});
$("#confirm").click(function (e) {
e.preventDefault();
var delBtn = $('button[data-hash="'+$(this).data("hash")+'"]'); //Get specific delete button element by passed hash value
const act = delBtn.attr('data-act'); //Get data variables from the delete button element
const para = delBtn.attr('data-para');
const hash = $(this).data("hash");
$.ajax({
url: '/include/ajax/mark_sold.php',
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
delBtn.closest('div.card').hide(); //Find closest .card element to the specified delete button
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
Don't forget to add .deleteBtn class to your delete buttons.
Hope it helps.

Modal dialog's onshow not called after postback

I have a Bootstrap modal dialog that I am using to populate with data when user clicks on "Edit" in a jQuery data table. There is a Cancel and Submit button on this modal.
When I open the modal and click Cancel and then select another table row and click "Edit", everything is fine; data gets populated correctly each time "Edit" is clicked. However, if I do a postback by clicking "Submit" on the modal and then click "Edit" again, modal opens and no data is there.
I am using modal's on('show.bs.modal', ...) to populate it and it never gets hit after a postback is done.
// This is called when "Edit" in data table row is clicked
function showEdit(var1, var2) {debugger
$('#hfVar1').val(var1);
$('#hfVar2').val(var2);
showEditModal();
}
function showEditModal() {debugger
$("#spnEditHeader").text("Edit Something");
$('#editModal').modal('show');
}
$(document).ready(function () {
// This populates the jQuery data table
showTable(somthing, anotherThing);
// This is executed as long there is no postback;
// once a postback is perfoemd this is not hit, modal not populated
$('#editModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function (e) {debugger
var var1= $('#hfVar1').val();
var var2= $('#hfVar2').val();
//make ajax call to populate items
populateMPOOEdit(var1, var2);
});
....
});
//This is the button in modal that causes postback
<div class="modal-footer">
<div id="divEditButtons" style="text-align: center;">
<button id="btnCancel" class="btn btn-info2" data-dismiss="modal" aria-hidden="true" aria-label="Cancel">Cancel</button>
<button id="btnSubmit" class="btn btn-primary" aria-hidden="true" aria-label="Update">Update</button>
</div>
</div>
// "Submit" button's click handler
$(document).on("click", "#btnSubmit", function (event) {
// Validate data (client side validation)
var isValid = validateUpdate();
// Also need a server side validation checking for duplicate name, using ajax to do this
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("services/mpoo.asmx/NameExists") %>',
cache: false,
data: JSON.stringify({ "Name": name }),
}).done(function (data) {
var result = data.d;
if (result != '') {
nameExists = JSON.parse(data.d);
if (nameExists == "true") {
$("#lblErrName").text("Duplicate Name");
$("#lblEditErrName").show();
isValid = false;
}
if (isValid) {
__doPostBack('btnSubmit', JSON.stringify({
action: "SaveUpdate", Var1: var1, ..., Varn: varn
}));
$('#editModal').modal('hide');
}
}
});
return false; // to prevent modal from closing if there are errors on page
});
Create a function like this:
//basically everything you had in your document.ready function
function myJsFunc() {
// This populates the jQuery data table
showTable(somthing, anotherThing);
// This is executed as long there is no postback;
// once a postback is perfoemd this is not hit, modal not populated
$('#editModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function (e) {debugger
var var1= $('#hfVar1').val();
var var2= $('#hfVar2').val();
//make ajax call to populate items
populateMPOOEdit(var1, var2);
});
....
}
Then in your Page_Load event handler in your codebehind, try putting this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "some random name for your script", "myJsFunc();", true);

After show Modal Window jQuery validation plugin doesn't work

I have a problem with jQuery Validation Plugin.
I used ASP.NET MVC with Entity Framework. The project has a lot of libraries and it's hard to understand the problem and find answer.
I have a form on which the section with fields. I used validation plugin for validate client-side fields.
The section is collapsible and can to be open and closed. Inside section I have button for open modal window. Inside window I can to search data used Ajax. User can to add information manually, can add information used Ajax and fields can be empty.
The first task is to add validation for hidden fields.
I added setDefault for validator inside $(document).ready:
jQuery.validator.defaults.ignore = "";
When I added setting ignore for validator, everything work fine with hidden fields and open fields but after showing modal window validator plugin doesn't work. In FireBug I take error: TypeError: validator is undefined (twice).
I open and close the modal window (without Ajax search) and I take this error and validator doesn't work.
This is modal window code:
#using (modal.BeginBody()){
<div class="row">
<div class="col-lg-offset-3 col-lg-6" id="search-entry-form">
#using (var form = Html.Bootstrap().Begin(new Form().HtmlAttributes(new { onsubmit = "return false" })))
{
#form.FormGroup().TextBoxFor(model => model.EANCode).Label();
#form.FormGroup().TextBoxFor(model => model.Name).Label();
#form.FormGroup().TextBoxFor(model => model.InternationalName).Label();
#Html.Bootstrap().Div(Html.Bootstrap().SubmitButton().Text("Wyszukaj").Id("search-specific").Style(ButtonStyle.Success).
ButtonBlock().PrependIcon("glyphicon glyphicon-search")).Class("col-lg-5 col-lg-offset-7");
}
</div>
</div>
<div class="col-lg-12 top30" id="result-table"></div>}#using (modal.BeginFooter()){#Html.Bootstrap().Button().Text("Zamknij").Data(new { dismiss = "modal" }).Style(ButtonStyle.Primary)}
I this file I added Bundels with Ajax code:
#Scripts.Render("~/bundles/specificNutSearch")
This is Ajax code:
$(document).ready(function () {
function pagination() {
$('#result-table').each(Utils.Pagination);
}
function getData(id) {
$.ajax({
url: "GetSpecific",
dataType: "json",
method: "POST",
cache: false,
data: {
id: id
},
}).success(function (result) {
if (result === null) return;
for (var propName in result) {
$(".panel [Name$='." + propName + "']").val(result[propName]);
}
clear();
});
}
function clear() {
$("#result-table").html("");
$(".modal input").val("");
$(".pager").remove();
}
function search() {
var form = $("#search-entry-form :input").serialize();
$.ajax({
url: $('#search-entry-form form').attr('action'),
dataType: "html",
method: "POST",
cache: false,
data: form
}).success(function (result) {
$("#result-table").html(result);
$(".select-specific").on("click", function () { getData($(this).data("specific")) });
pagination();
});
}
$("#search-specific").on("click", search);});
This is the field code which need validate:
Html.Bootstrap().Div(
Html.Bootstrap().Label("").LabelText("4.").Class("pull-left"),
Html.Bootstrap().FormGroup().TextBoxFor(model => model.EAN).Label()).Class("col-lg-6")
In the chhtml view I added modal window on the bottom file:
<div class="modal fade" id="specificNutritionalPurposeSearch" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
It is ViewModel field:
[Display(Name = "Kod EAN")]
[RegularExpression("[0-9]{13}",ErrorMessage = "Kod EAN powinien zawierać 13 znaków")]
public string EAN { get; set; }
Also found a very strange thing:
When I Comment out the all specificNutSearch (#Scripts.Render("~/bundles/specificNutSearch")) code, the plugin does not work.But when I comment out #Scripts.Render("~/bundles/specificNutSearch" line, plugin works.
What could be the problem? Maybe that's a problem of incompatibility of versions jQuery and Validator Plugin?
EDIT:
This is button code for open model window:
#Html.Bootstrap().Button().Text("Wyszukaj środek spożywczy").TriggerModal("specificNutritionalPurposeSearch").HtmlAttributes(new { href = Url.Action("SearchSpecificNutritionalPurpose") }).Style(ButtonStyle.Success).ButtonBlock().PrependIcon("glyphicon glyphicon-search")
This is ActionResult in Controller:
[HttpGet]
public ActionResult SearchSpecificNutritionalPurpose()
{
var model = new SpecificNutritionalPurposeSearchViewModel();
return PartialView("Modals/_SpecificNutritionalPurposeDictionarySearch", model);
}
In action model empty because modal window has button for searching data.
This is ActionResult for search button in modal window for searching data:
[HttpPost]
public virtual ActionResult SearchSpecificNutritionalPurpose(SpecificNutritionalPurposeSearchViewModel searchParameters)
{
var searchResult = _dictionaryRepository.FindSpecificNutritionalPurpose(searchParameters.EANCode, searchParameters.Name, searchParameters.InternationalName).Take(100).ToList();
return PartialView("Modals/_SpecificNutritionalPurposeSearchResult", searchResult);
}
Method FindSpecificNutritionalPurpose take data from dataBase (EF)
I think that when the specyficNutSearch script alters the DOM the validation handlers are getting removed.
My solution is to change clear method so it will refresh validation handlers:
function clear() {
$("#result-table").html("");
$(".modal input").val("");
$(".pager").remove();
//add this
var $form = $("#search-entry-form form");
$form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($form);
}

Rails: don't refresh page after modal action/submit

I have a modal which opens on top of another screen. The base screen has a filter method that uses AJAX to filter the results on that page.
After, I filter the results on the screen, I can open the modal and perform an action on the form in the modal. However, I don't want to perform a redirect/refresh.
How do I do this while still performing the submission?
My modal link is like:
<%= link_to this_path(user_id: user.id), class:"modal-link", data: {"modal-url" => this_path(user_id: user.id)} do %><span><i class="fa fa-plus"></i><% end %>
The modal is standard enough:
<div class="modal form-modal">
<div class="modal-container">
<div class="modal-dialog modal-dialog-wide">
<button class="close">×</button>
<div class="modal-content">
<div class="modal-header">
<h2 class="hdg-b">Edit This</h2>
</div>
<div class="modal-body">
<div id="error_explanation"></div>
<%= render 'form', form_path: action_path, form_method: :put, create: false %>
</div>
</div>
</div>
</div>
</div>
The AJAX is too:
MyProject.onPageLoad(function() {
var form = $('.edit_site_scope'),
onSubmit = function(event) { //callback handler for form submit
event.preventDefault();
var form = $(this),
url = form.attr("action"), //get form action:
type = form.attr("method"),
data = form.serialize();
var location = window.location.href;
var posting = $.ajax({
type: type,
url: url,
data: data,
dayaType: "json",
success:function(data, textStatus, jqXHR)
{
$('.modal').remove();
window.location = location;
$('#contact-tab-submit').show();
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#error_explanation').html('');
errors = jqXHR.responseJSON;
$.each( errors, function( key, value ) {
$('#error_explanation').append('<div class="alert alert-dismissable" id="alert-message"><i class="fa fa-exclamation-triangle"></i>' + value + '<div class="alert-close">Close</div></div>');
});
$('#contact-tab-submit').show();
}
});
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000);
return false; // prevent default when submit button clicked
};
if (form.size() !== 0) {
form.submit(onSubmit);
}
});
And here is my controller action on the form submit:
def action_to_be_performed
#this_thing = ThisThing.where(id: params[:id]).first
#this_thing.update(this_things_params)
flash[:success] = "Successfully performed the action."
render json: #this_thing
rescue => error
Rails.logger.error "Exception caught updating this.\nCause: #{error}\n" + error.backtrace.join("\n")
render json: #this_thing.errors.full_messages, status: :bad_request
end
I really struggle with modals still and I guess with AJAX. How do I perform my action, close the modal and keep the current page open?
I figured out a simple solution on the drive home. The following line in my Javascript:
window.location = location;
can be changed to:
window.location.reload();

How to show Ajax response as modal popup

I have a link on clicking it is sending ajax request and getting response successfully which is html file and I am appending to a div, but I need to show that div as modal popup and I tried something below.
in html file
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
<div id="login_for_review" data-toggle="modal" data-target="#reviewLoginModal"></div>
in js file
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');// I tried to show this response as modal popup
},
error: function(output){
alert("fail");
}
});
});
output file
<div class="centerForm modal fade" role="dialog" style="margin-left: 35%;" id="reviewLoginModal">
<div class="modal-dialog modal-sm" >
<div class="modal-content">
// here I have login form
</div>
</div>
but I am not getting this html output as modal pup instead I am getting black screen can anyone help me how to do this?
In Bootsrap modal popup, You can use plain way to show modal which don't need pre-defined modal div container . see at modal
For E.g
$.ajax({
url: "url",
type: 'POST',
dataType: "html",
data:{id:params},
success: function(data, status, xhr) {
if(data==""){
window.location.href="/";
}
else{
BootstrapDialog.show({
title: "Modal Tital",
message: function(dialogRef){
$mydata = $($.parseHTML(data));
return $mydata;
},
onshow: function(dialog){
// and css change if need, eg.
dialog.$modalHeader.css("float","none");
},
onshown:function(dialog)
{
// event after shown
},
onhide:function(dailog)
{
// event on hide
}
});
}
},
statusCode: {
401: function () {
alert("Your session has been expired");
}
}
});
I solved this problem by creating modal and by removing data-toggle and data-target and just appending response to that modal div
Code For modal div
<div id="login_for_review" class="modal hide" role="dialog">
</div>
Code For hyperlink
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
Code For ajax call
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');//now its working
},
error: function(output){
alert("fail");
}
});
});

Categories

Resources