I have this script that takes the data from my database with GET and shows them in the HTML and then updates in the database when I press on the checkbox, however when I press the checkbox, the PUT is done three time. Does anyone know how to solve this?
Any help is welcome.
Code below:
$.ajax({
type: 'GET',
async: false,
url: 'https://app.myapp.com/reservations',
success:function(reservations){
reservas.forEach (function (reservation) {
var HTML = [];
HTML.push('<tr class="reservations">');
HTML.push('<td> <input type="checkbox" class="checkbox" data-id="' + reservation._id + '" data-nome="' + reservation.nome + '" data-email="' + reservation.email + '" /> </td>');
HTML.push('<td>' + reservation._id + '</td>');
HTML.push('<td>' + reservation.nome + '</td>');
HTML.push('<td>' + reservation.email + '</td>');
HTML.push('</tr>');
$('tbody').append(HTML.join(""));
$(function(){
$(document).on('click', '.checkbox', function(){
console.log('salvo');
var update = $(this);
$.ajax({
type: 'PUT',
url: 'https://localhost/datas',
data: {
_id: update.attr('data-id'),
nome: update.attr('data-nome'),
email: update.attr('data-email'),
},
sucess:function (success) {
alert('updated!!');
},
error:function(err) {
console.log(err);
}
});
});
});
})
},
error:function(e){
console.log(e);
}
});
The problem is that you are adding the event on each iteration. You should take the Event listener function out of that .each. As you are using the jQuery function on over the document itself, you can take that event listener completely out of your ajax function and it will be listening the click on the checkbox anyway (because, as mentioned, you are binding the event to the document and not to the checkboxes themselves, so you don't need them to exist before you bind the event).