-
Notifications
You must be signed in to change notification settings - Fork 77
/
scripts.js
80 lines (71 loc) · 2.4 KB
/
scripts.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
$(function() {
// GET/READ
$('#get-button').on('click', function() {
$.ajax({
url: '/products',
contentType: 'application/json',
success: function(response) {
var tbodyEl = $('tbody');
tbodyEl.html('');
response.products.forEach(function(product) {
tbodyEl.append('\
<tr>\
<td class="id">' + product.id + '</td>\
<td><input type="text" class="name" value="' + product.name + '"></td>\
<td>\
<button class="update-button">UPDATE/PUT</button>\
<button class="delete-button">DELETE</button>\
</td>\
</tr>\
');
});
}
});
});
// CREATE/POST
$('#create-form').on('submit', function(event) {
event.preventDefault();
var createInput = $('#create-input');
$.ajax({
url: '/products',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: createInput.val() }),
success: function(response) {
console.log(response);
createInput.val('');
$('#get-button').click();
}
});
});
// UPDATE/PUT
$('table').on('click', '.update-button', function() {
var rowEl = $(this).closest('tr');
var id = rowEl.find('.id').text();
var newName = rowEl.find('.name').val();
$.ajax({
url: '/products/' + id,
method: 'PUT',
contentType: 'application/json',
data: JSON.stringify({ newName: newName }),
success: function(response) {
console.log(response);
$('#get-button').click();
}
});
});
// DELETE
$('table').on('click', '.delete-button', function() {
var rowEl = $(this).closest('tr');
var id = rowEl.find('.id').text();
$.ajax({
url: '/products/' + id,
method: 'DELETE',
contentType: 'application/json',
success: function(response) {
console.log(response);
$('#get-button').click();
}
});
});
});