jquery destroy modal dialog on close - javascript

I have a jquery modal dialog which is created as follows in a function:
function EditDialog(pk) {
$.ajax({
url: "{% url 'populatereviewform' %}",
method: 'GET',
data: {
pk: pk
},
success: function(formHtml){
//place the populated form HTML in the modal body
$('.modal-body').html(formHtml);
$( "#dialog" ).modal({width: 500, height: 500});
},
dataType: 'html'
});
return false;
}
How can I ensure that every time I call this function a fresh instance of the dialog is created? I wonder if somehow I can hook into the close event and ensure that the dialog is completely destroyed. I am trying to debug something and it seems that some of my variables do not get refreshed when this dialog is called a second time and I am trying to get to the bottom of it. The django template for creating the dialog is:
<div id="dialog" class="modal" title="Edit" style="display:none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Review Uploaded Image</h4>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>

You can use the bootstrap modal callback.
$('#dialog').on('hidden.bs.modal', function () {
$('.modal-body').html('');
});

Related

how to pass variable from js to modal [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Hi friends I just wanted to pass a variable to my modal from the script. I am using CodeIgniter as frame work which enables me to generate table with its built-in library. When I press the view button on my table it gets the corresponding id, gets back to controller to grab the table content and returns the table content to the script.
Now I have the data in the script called “data[‘viewTable’]” and in my modal id called body have the function call $this->table->generate($tabledata). I just wanted to use the data I have in the script to be in the place of variable $tabledata as it becomes $this->table->generate(data[‘viewTable’]) the question how do I get this data from the script.
I have searched for related problems on google but what I got changes the whole content of the modal specified by id. U may suggest me to generate a table inside the script and change the modal by using innerHTML but I tried and still it doesn’t work.
Here is partial view of my code
<div id="view_modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="title">View schedules</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="body">
<?php
//how do I get the variable in the script to be used in the place of $viewTable
echo $this->table->generate($viewTable);
?>
</div>
<div class="modal-footer">
<button type="button" class="saveview btn btn-primary">Save</button>
<button type="button" class="closeview btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
An on the script I have
$(document).on('click', '.view', function () {
var id = $(this).data('id');
var formdata = '&action=viewschedule&ajax=1&id=' + id;
$.ajax({
async: false,
type: "POST",
data: formdata,
dataType: "json",
success: function (data) {
//Here i got data from the database and I want to pass to modal id 'body'
$('#view_modal').show();
}
});
});
Based on your updated question, you need to just target your #body and updated the html. Here's how you'd do that with the jQuery you're already using
$('#body').html(data.viewTable);
Solution
$(document).on('click', '.view', function () {
// Shortcut for the demo, delete this part
var data = {viewTable: '<table><tr><td>Hello</td></tr></table>'}
$('#body').html(data.viewTable);
$('#view_modal').show();
// Your code, already updated to work.
var id = $(this).data('id');
var formdata = '&action=viewschedule&ajax=1&id=' + id;
$.ajax({
async: false,
type: "POST",
data: formdata,
dataType: "json",
success: function (data) {
$('#body').html(data.viewTable);
$('#view_modal').show();
}
});
});
#view_modal {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="view">View</button>
<div id="view_modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="title">View schedules</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="body"></div>
<div class="modal-footer">
<button type="button" class="saveview btn btn-primary">Save</button>
<button type="button" class="closeview btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Bootstrap modal not closing second time from JS code

I have following code in a Partial View in an MVC project:
$(document).ready(function () {
$("##Html.IdFor(m => m.AanwezigheidChauffeurID)").change(function () {
setModalBody("busy", "Even geduld, de gegevens worden opgehaald...");
$("#modalDialog").modal({ keyboard: false, backdrop: "static" });
var chauffeurRequest = $.ajax({
url: '#Url.Action("GetAanwezigheid", "Invoer")',
data: { id: $("##Html.IdFor(m => m.AanwezigheidChauffeurID)").val() },
async: true,
cache: false,
type: "POST"
});
chauffeurRequest.done(function (data, textStatus, jqXHR) {
$("#entriesDiv").empty();
$("#entriesDiv").append(data);
$(".hoursInput:first").trigger("change");
$("#modalDialog").modal("hide");
});
chauffeurRequest.fail(function (request, textStatus, errorThrown) {
setModalBody("error");
});
});
});
This is the markup of the modal:
<div class="modal fade" id="modalDialog" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalDialogLabel">Xwift</h5>
<button type="button" class="close closeModalButton" data-dismiss="modal" aria-label="Sluiten">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="modal-dialog-body" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" id="closeModalButton" disabled class="btn btn-primary closeModalButton" data-dismiss="modal">Sluiten</button>
</div>
</div>
</div>
</div>
The situation:
$("##Html.IdFor(m => m.AanwezigheidChauffeurID)") is referring to a select element. When I change the value of the drop-down, the AJAX request is launched and the modal dialog is shown. When the request is done, the modal is closed by calling $("#modalDialog").modal("hide");.
Now when I change the value of the drop-down again, the request is launched again and the modal is shown again. When the request is done, I can see the changes in the DOM through the backdrop from the modal, but the modal won't close anymore. When I call the line $("#modalDialog").modal("hide"); in the console to test it, the modal does close.
Is there some reason why it won't close the second, third or more time?
Too bad I already asked this question before finding following question here on StackOverflow: Bootstrap 4 Modal Not Closing Properly On Hide
Several comments and answers refer to the fact that the fade class disrupts the whole hiding of the modal. I have tried removing this class and it worked for me as well. Sadly, I didn't find a reason for this.

Bootstrap 4 load modal-Content from other page [duplicate]

I can't make the Modal work in the remote mode with the new Twitter Bootstrap release : Bootstrap 4 alpha. It works perfectly fine with Bootstrap 3. With bootstrap 4 I am getting the popup window, but the model body is not getting loaded. There is no remote call being made to myRemoteURL.do to load the model body.
Code:
<button type="button" data-toggle="modal" data-remote="myRemoteURL.do" data-target="#myModel">Open Model</button>
<!-- Model -->
<div class="modal fade" id="myModel" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title" id="myModalLabel">Model Title</h3>
</div>
<div class="modal-body">
<p>
<img alt="loading" src="resources/img/ajax-loader.gif">
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
Found the problem: They have removed the remote option in bootstrap 4
remote : This option is deprecated since v3.3.0 and will be removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
I used JQuery to implement this removed feature.
$('body').on('click', '[data-toggle="modal"]', function(){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
});
According to official documentation, we can do the follow(https://getbootstrap.com/docs/4.1/components/modal):
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
So, I believe this is the best approach (works for BS 5 too):
<!-- Button trigger modal -->
<a data-bs-toggle="modal" data-bs-target="#modal_frame" href="/otherpage/goes-here">link</a>
<!-- Modal -->
<div class="modal fade" id="modal_frame" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<!-- Completes the modal component here -->
</div>
<script>
$('#modal_frame').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load(e.relatedTarget.href);
});
</script>
e.relatedTarget is the anchor() that triggers the modal.
Adapt to your needs
As some of the other answers and Bootstrap docs indicate, Bootstrap 4 requires handling the show.bs.modal event to load content into the modal. This can be used to either load content from an HTML string, or from a remote url. Here's a working example...
$('#theModal').on('show.bs.modal', function (e) {
var button = $(e.relatedTarget);
var modal = $(this);
// load content from HTML string
//modal.find('.modal-body').html("Nice modal body baby...");
// or, load content from value of data-remote url
modal.find('.modal-body').load(button.data("remote"));
});
Bootstrap 4 Remote URL Demo
Another option is to open the modal once data is returned from an Ajax call...
$.ajax({
url: "http://someapiurl",
dataType: 'json',
success: function(res) {
// get the ajax response data
var data = res.body;
// update modal content
$('.modal-body').text(data.someval);
// show modal
$('#myModal').modal('show');
},
error:function(request, status, error) {
console.log("ajax call went wrong:" + request.responseText);
}
});
Bootstrap 4 Load Modal from Ajax Demo
In Asp.NET MVC, this works for me
html
Edit item
<div class="modal" id="modalPartialView" />
jquery
<script type="text/javascript">
function Edit(id)
{
$.ajax({
url: "#Url.Action("ActionName","ControllerName")",
type: 'GET',
cache: false,
data: {id: id},
}).done(function(result){
$('#modalPartialView').html(result)
$('#modalPartialView').modal('show') //part of bootstrap.min.js
});
}
<script>
Action
public PartialViewResult ActionName(int id)
{
// var model = ...
return PartialView("_Modal", model);
}
If you use the Jquery slim version (as in all the Bootstrap 4 docs and examples) the load function will fail
You need to use the full version of Jquery
This process is loading the current dynamic. data remote = "remoteContent.html"
<!-- Link trigger modal -->
<a href="javascript:void(0);" data-remote="remoteContent.html" data-toggle="modal" data-target="#myModal" data-remote="true" class="btn btn-default">
Launch Modal
</a>
This trick : data-remote="remoteContent.html"
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

Hide a dynamic element function on.('hide')

I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?
Thanks
function openModalFromUrl(modal_url, close_function = function(){}) {
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
data: {
'_token': token,
},
url: modal_url,
type: 'POST',
success: function(html) {
// create a new modal div
var modal = document.createElement("div");
$(modal).addClass('modal fade');
$(modal).attr( "role", "dialog" );
$('body').append(modal);
// place response in the modal
$(modal).html(html)
// open the modal
$(modal).modal('show');
// THIS FIRES IMMEDIATELY
$(modal).on('hide', window[close_function]() );
},
error: function() {
bootbox.alert('Error');
}
});
}
The issue is in this line :-
$(modal).on('hide', window[close_function]() );
Change it to :-
$(modal).on('hide', window[close_function] );
Explanation :-
In JavaScript when we provide a function as a reference, we use it's name without any parenthesis
i.e. 'my_func' not 'my_func()'
As 'my_func()' give the result of the function as reference not the function itself.
So just remove the parenthesis and your problem is solved.
According to the documentation you should use hidden.bs.modal event. Also no need in checking the window object for the function, just pass it.
$('#myModal').modal('show');
var close_function = function () {
console.log('closed');
}
$('#myModal').on('hidden.bs.modal', close_function);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<div class="modal fade" id='myModal' abindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Thank you to all for your answers. I have found the solution.
As the modals were dynamically generated i had to change the call to:
$('body').on('hide.bs.modal', modal, window[close_function] );
Now it works like a charm. Thanks again to everyone!

How to open bootstrap modal in ajax success

I want to open bootstrap modal through jquery. I know ajax in running to success as it throws alerts. But cannot open modal. These are my code.
$.ajax({
type: "POST",
url: "<?php echo base_url() . 'index.php/application/requestCode'; ?>",
data: {
'apiName': apiName,
'api': api,
'hotel': hotel,
'payment':payment,
'template': template
},
success: function(msg)
{
$("#getCodeModal").modal("toggle");
$("#getCode").html(msg);
}
});
And my modal HTML is:
<!-- Modal -->
<div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"> API CODE </h4>
</div>
<div class="modal-body" id="getCode" style="overflow-x: scroll;">
//ajax success content here.
</div>
</div>
</div>
</div>
In error in console: modal is not a function.
try with this
success: function(resp){
$("#getCode").html(resp);
$("#getCodeModal").modal('show');
}
Try this one:
success: function(data) {
$("#getCode").html(data);
jQuery("#getCodeModal").modal('show');
}
This should work :).
Write down the following code.
success: function(msg)
{
$("#getCodeModal").modal("show");
$("#getCode").html(msg).show();
}
this happen when you include library jquery twice. check for that, maybe you include it in your index and then again unnecessarily in you partial page.
after toggling the modal for the first time, you have to toggle it once again to "turni it off".. and on the success function toggle it and it will appear normally.
example:
$('#Modal').modal('toggle) //this is the first time to toggle the modal
$('#Modal').modal('toggle) //this is the second time "to turn it off"
success:function(){
$('#Modal').modal('toggle) //this is the third time to "turn it on again"
}

Categories