-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
91 lines (75 loc) · 2.69 KB
/
script.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
81
82
83
84
85
86
87
88
89
90
91
//javascript ready function, so that everything is loaded before running the code
$(function(){
//get products
$('#getProducts').on('click',function(){
$.ajax({
url:'/products',
contentType:'application/json',
success:function(response){
var tbodyEl=$('#getElements');
tbodyEl.html('');
response.products.forEach(function(product){
tbodyEl.append('\
<tr>\
<td class="id">'+product.id+'</td>\
<td> <input type="text" class="productName" value="'+product.name+'"></td>\
<td> <button class="updateBtn">Update/Put product</button>\
<button class="deleteBtn">Delete product</button>\
</td>\
</tr>\
');
});
}
});
});
//Create/post
$('#createProductForm').on('submit',function(event){
event.preventDefault();
var createInput=$('#createInput');
$.ajax({
url:'/products',
method:'POST',
contentType:'application/json',
data:JSON.stringify({ //to send the data to the server
name: createInput.val()
}),
success:function(response){
console.log(response);
createInput.val('');
$('#getProducts').click();
}
})
});
//UPDATE/ PUT
$('table').on('click','.updateBtn',function(){
var rowEl=$(this).closest('tr');//this->to access the html element that is being retrieved
var id=rowEl.find('.id').text();
var updatedProduct=rowEl.find('.productName').val();
$.ajax({
url:'/products/' + id,
method:'PUT',
contentType:'application/json',
data:JSON.stringify({ //to send the data to the server
newName: updatedProduct
}),
success:function(response){
console.log(response);
$('#getProducts').click();
}
});
});
//DELETE
$('table').on('click','.deleteBtn',function(){
var rowEle=$(this).closest('tr');
var id=rowEle.find('.id').text();
$.ajax({
url:'/products/' + id,
method:'DELETE',
contentType:'application/json',
success:function(response){
console.log(response);
$('#getProducts').click();
}
});
});
});