Tengo un botón que abre un modal pero he impedido que el modal se cierre haciendo clic en el fondo o la tecla ESC.
Mi botón se ve así:
<button data-toggle="modal" data-target="#CompanyProfile"data-backdrop="static" data-keyboard="false">Click </button>
¿Cómo cierro este modal después del éxito de $.ajax
usando jQuery?
Hice algunas pruebas: el modal se cerró pero el fondo se bloqueó y no puedo hacer nada hasta que actualice la página
Para cerrar el modal de arranque, puede pasar 'ocultar' como opción al método modal de la siguiente manera.
$('#CompanyProfile').modal('hide');
Use este código dentro del éxito de ajax.
Agregar esta solución ya que no parece haber un método genérico en la lista.
Si desea cerrar cualquier modal en caso de éxito, pero no desea crear manualmente cada llamada $.ajax al servidor, puede usar lo siguiente:
$('.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'); } } }); });
Aparte, si está buscando usar el código anterior como copiar/pegar, necesitará lo siguiente, que toma los datos del formulario y los convierte en JSON para publicarlos en el servidor, o cambie $(this).serializeObject()
a $(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; };
Referencia: Bootstrap JS Modal
Puedes intentar algo como
$( 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); } }) }); });
Asegúrese de que el modal se inicie solo una vez