connie connie - 1 month ago 6
Ajax Question

insert multiple records after calling ajax with bootrap modal

I'm workong on ASP.NET CORE project. I use Bootstrap's modal in one view and call ajax to insert new record in database. There's few inputs field, save and close buttion in bootstrap modal dialog. After first time I click save, the Bootstrap's modal will disappear and a new record will be inserted in DB table. However, it will insert two records when I open the modal and click save again.

Moreover, it will insert three records if I open the modal to input and save again.

It seems it always keep reserve previous insert instance session. I have spent few hours working on it but still faild.

I appreciate your help and suggestion. Thanks.

FYI:

$('#exampleModal').on('show.bs.modal', function (event)

{
var modal = $(this);
modal.find('.modal-title').text('New Record');
modal.find('#saveNewServiceRecord').click(function () {
_addActivity();

});
});


$('#exampleModal').on('hidden.bs.modal', function () {
var modal = $(this);
modal.find('.modal-body input').val('');

});





function _addActivity() {
var data = {
ActivityDetails: $('#message-text').val(),
TicketID: id
};

$.ajax({
url: "/Record/Create",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(data),
success: function (result) {

_getRecordList();
},
error: function(errormessage) {
alert(errormessage.responseText);
}
});
}

Answer

You're attaching the click event every time the show.bs.modal event is fired.

modal.find('#saveNewServiceRecord').click(function () {
     _addActivity();
}

You need to define this click event outside of the show.bs.modal event, or you can unbind it in the hidden.bs.modal event. I recommend using on and off for unbinding events.

Or use this below:

$('#exampleModal').on('show.bs.modal', function (event)  {
      var modal = $(this);
      modal.find('.modal-title').text('New Record');
})
.on('click', '#saveNewServiceRecord', function() {
    _addActivity()
});
function _addActivity() {
   // your code
}