forked from BrunoMarcos18/exercicioJavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRUD.js
65 lines (57 loc) · 2.03 KB
/
CRUD.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
$(document).ready(function () {
listAnimals();
$('#animal_form').submit(function (e) {
e.preventDefault();
const animalName = $('#animal_name').val();
$.post('http://cafepradev.com.br:21020/animals/insert', { animal: animalName }, function () {
$('#animal_name').val('');
listAnimals();
});
});
function listAnimals() {
$.get('http://cafepradev.com.br:21020/animals/list', function (data) {
const animalList = $('#animal_list');
animalList.empty();
data.forEach(function (animal) {
animalList.append(`
<tr>
<td>${animal.id}</td>
<td>${animal.animal}</td>
<td>
<button class="edit-btn" data-id="${animal.id}">Editar</button>
<button class="delete-btn" data-id="${animal.id}">Deletar</button>
</td>
</tr>
`);
});
$('.edit-btn').click(function () {
const animalId = $(this).data('id');
editAnimal(animalId);
});
$('.delete-btn').click(function () {
const animalId = $(this).data('id');
deleteAnimal(animalId);
});
});
}
function editAnimal(id) {
const newAnimalName = prompt('Editar Nome do Animal:');
if (newAnimalName !== null) {
$.ajax({
url: `http://cafepradev.com.br:21020/animals/update/${id}`,
type: 'PUT',
data: { animal: newAnimalName },
success: listAnimals,
});
}
}
function deleteAnimal(id) {
if (confirm('Tem certeza que deseja deletar este animal?')) {
$.ajax({
url: `http://cafepradev.com.br:21020/animals/delete/${id}`,
type: 'DELETE',
success: listAnimals,
});
}
}
});