How do I close a modal window after AJAX success
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
You can try something like
$( document ).ready(function() {
$(".btn").button().click(function(){ // button click
$('#CompanyProfile').modal('show') // Modal launch
$.ajax({
type: "POST",
url: "url",
data:{data:data},
cache: false,
success: function(data) {
$('.text').html(data);
}
})
});
});
Make sure the modal is launched only once