-
Notifications
You must be signed in to change notification settings - Fork 1
/
restaurant_like_button.js
67 lines (58 loc) · 2.21 KB
/
restaurant_like_button.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
function encodeForAjax(data) {
return Object.keys(data).map(function(k){
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&')
}
async function addRestaurantLike(restaurantId,userId) {
return fetch('add_restaurant_like.php', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: encodeForAjax({restaurantId:restaurantId,userId:userId})
})
}
function getUserId(){
return fetch('get_user_id.php')
.then(res => res.json())
}
async function removeRestaurantLike(restaurantId,userId) {
return fetch('remove_restaurant_like.php', {
method: 'delete',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: encodeForAjax({restaurantId:restaurantId,userId:userId})
})
}
const restaurantLikeButtons = document.getElementsByClassName("likeRestaurant")
async function addListeners(){
let userId = await getUserId()
for(const likeButton of restaurantLikeButtons){
likeButton.addEventListener('click', async function(event){
event.target.classList.toggle("like-no");
event.target.classList.toggle("like-yes");
const restaurantId = event.target.classList[0]
const nrLikes = likeButton.nextElementSibling
const previousLikes = parseInt(nrLikes.innerHTML)
if (event.target.classList.contains("like-yes")) {
console.log("✅💾 Saving Favorite...")
addRestaurantLike(restaurantId,userId)
.catch(() => console.error('Network Error'))
.then(response => response.json())
.catch(() => console.error('Error parsing JSON'))
.then(json => console.log(json))
nrLikes.innerHTML=(previousLikes+1)
} else {
console.log("❌ Removing Favorite...")
removeRestaurantLike(restaurantId,userId)
.catch(() => console.error('Network Error'))
.then(response => response.json())
.catch(() => console.error('Error parsing JSON'))
.then(json => console.log(json))
nrLikes.innerHTML=(previousLikes-1)
}
})
}
}
addListeners()