I have a button which opens a modal but I have prevented the modal close by clicking background or ESC key.
My button looks like this:
<button data-toggle="modal" data-target="#CompanyProfile"data-backdrop="static" data-keyboard="false">Click </button>
How do I close this modal after $.ajax
success using jQuery?
I have done a few tests - the modal has closed but the background gets locked, and I cannot do anything until I refresh the page
After you get success response you can simply a. modal("closeModal"); to close your modal.
Modals are built with HTML, CSS, and JavaScript. They're positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead. Clicking on the modal “backdrop” will automatically close the modal.
To close bootstrap modal you can pass 'hide' as option to modal method as follows.
$('#CompanyProfile').modal('hide');
Use this code inside ajax success.
Fiddle Demo
Adding this solution since there doesn't seem to be a generic method listed.
If you wish to close any modal on success, but don't wish to hand-craft each $.ajax call to the server, you could use the following :
$('.modal form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $(this).serializeObject(),
contentType: 'application/json',
beforeSend: function(xhr){xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")},
success: function(data) {
console.log(data.success);
if(data.success===1) {
// loop through all modal's and call the Bootstrap
// modal jQuery extension's 'hide' method
$('.modal').each(function(){
$(this).modal('hide');
});
console.log('success');
} else {
console.log('failure');
}
}
});
});
As an aside, if you are looking to use the code above as copy/paste, you will need the following which takes form data and converts it into JSON for posting to the server, or change the $(this).serializeObject()
to $(this).serialize()
:
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
o = { request: o };
return o;
};
Reference: Bootstrap JS Modal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With