Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

2.8K
Visualizações
How do I close a modal window after AJAX success

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

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda