unable to close modal window after ajax success call

3.6k Views Asked by At

I am making a jquery ajax request as follow

Edit

On click of edit btn

$('.mymodalbtn').click(function($this){
            var id = $this.data('id'); 
            $('[name="id"]').val(id);
        });
    });

Modal window get open with editable fields, On form submit I am making a ajax call as below

$('#mymodalForm').on('submit',function(e){
            e.preventDefault();
            var successFlag=false;

            $.ajax({
                url: "/student/"+selectedId ,
                data : {'id':selectedId},
                type: 'PUT',
                datatype: "json",
                success: function(data){
                    $.gritter.add({
                        title: "Student",
                        text: data,
                        time: '1000'
                    }),
                }
            });
        });

<!-- Nifty Modal HTML -->
    <div class="md-modal colored-header md-effect-9" id="mymodalWin">
        <div class="md-content">
            <div class="modal-header">
                <h3>Student</h3>
            </div>
            <form id="mymodalForm" method="post" action="">
            <div class="modal-body form">   
                <input type="text" value="2" name="id"/>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default btn-flat md-close" data-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary btn-flat" id="edit-selected-transaction" data-dismiss="modal">Submit</button>
            </div>
            </form>
        </div>
    </div>
    <div class="md-overlay"></div>  

I am trying to auto-close modal window if it's successful else show error and stay on modal window.

I tried with .complete but no luck seems something wrong!.

I have tried .hide() also but then on click of edit button modal window doesn't appear. Can someone tell me how can I auto close bootstrap modal window.

2

There are 2 best solutions below

0
On

If you want to autoclose the modal window in the success callback then just do

$.ajax({
 success:function(data){
   $('#mymodal').modal('hide');
   // Rest of your code.
  }
});
3
On

Within your ajax call, use it like this....

$.ajax({
 success:function(data){
   $.gritter.add({
         title: "Student",
         text: responseHTML,
         time: '1000'
    },
 complete: function(){
            $('#mymodal').hide();
            //Here, you are executing your event loop, or in this example the api "hide" for the "#mymodal" id element.
    }
}); // I forgot a bracket here, my apologies.