I wanted to have a like button which will update the Likes field in the CMS. I’m not a code guy, so I’m not sure about this. Will this work?
[Yes, here is an example of how you could create a “like” button that increases the number of likes in a collection item using JavaScript and stores it using the Webflow CMS API:
// Attach click event to the like button
document.querySelector('.like-button').addEventListener('click', function() {
// Get the current number of likes
var currentLikes = parseInt(document.querySelector('.like-count').innerHTML);
// Increase the number of likes by 1
var newLikes = currentLikes + 1;
// Update the "Likes" field in the collection using the Webflow API
updateLikes(<ITEM_ID>, newLikes);
// Update the like count on the page
document.querySelector('.like-count').innerHTML = newLikes;
});
// Update the "Likes" field in the collection item
function updateLikes(itemId, likes) {
var xhr = new XMLHttpRequest();
xhr.open("PATCH", `https://api.webflow.com/collections/<COLLECTION_ID>/items/${itemId}`, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer <API_KEY>");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(`Likes for item ${itemId} updated to ${likes}`);
} else {
console.error(xhr.responseText);
}
};
var data = JSON.stringify({fields: {likes: likes}});
xhr.send(data);
}
You should replace <COLLECTION_ID> and <ITEM_ID> with the appropriate values for your collection and item, and <API_KEY> with the key you generated in Webflow settings.
Also, you’ll need to make sure that you have the right credentials to access the Webflow CMS API, and you should implement proper user authentication and authorization to prevent unauthorized access to the data.]
What do you guys think?