Categories
Development jQuery

i had to click twice to open modal after hide modal using jquery

I want to add new data using form in a modal(id=modal_add_item) and reload related datatable without refreshing the page.

I used $.post() to post the data to the specific page.

But, the modal did not disappear. Thus, I tried googling and found some solution.
From my intense searching, i found these guys:

$('#modal_add_item').hide();
$('.modal-backdrop').remove();
$('#form_add_item')[0].reset();

and then i tried applying it into my code:

$('#form_add_item').submit(function(event) {
    event.preventDefault();
    var button = $("#btn_add_item");
    var post_url = $(this).attr('action');
    var form_data = $(this).serialize()
    + '&' + encodeURI(button.attr('name'))
    + '=' + encodeURI(button.attr('value'));

    $.post(post_url, form_data, function(response) {
        if(response.includes("msgE")) {
            swal(
                'Error!',
                response.replace("msgE", ""),
                'error'
            )
        } else {
            swal(
                'Success!',
                response.replace("msg", ""),
                'success'
            )
        }

        $('#modal_add_item').hide();
        $('.modal-backdrop').remove();
        $('#form_add_item')[0].reset();
        func_reload();
    });
});

It works perfectly.. until I need to insert another data right after that process.
The button has to be clicked twice to open the dedicated modal.
Here, in case you need to see my code button

<button type="button" class="btn btn-sm btn-amber" data-toggle="modal" data-target="#modal_add_item">Add New Item</button>

What I need is that:-

  • The modal to disappear after the submit button is clicked.
  • The submitted data to be erased from the modal.
  • After post ajax response, display alert(in this case i used sweet alert) and in focus
  • Datatable refreshed(ajax.reload() is used)
  • No twice clicking to open modal after all of the above processes has been completed

image of twice clicking-GIF

Leave a Reply

Your email address will not be published. Required fields are marked *