How to open bootstrap modal in ajax success - javascript

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

Related

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

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!

jquery destroy modal dialog on close

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

Categories