I want to read a value from the firebase realtime database and then update the value by incrementing it with 1 and then update it again on the firebase realtime database.
The javascript function is attached to a HTML tag.
<div>
<a href="#" onclick="return LikeButton();">Link</a> <br><br>
</div>
In the image below, I want to update the value of Clicks by incrementing +1 everytime I click on the link inside the tag.
Here is the full code - clicks_count.html
I tried to first read the database using the get() function and then use the update() function to update the data aftering incrementing the read value by +1.
function LikeButton() {
const dbref = ref(db);
get(child(dbref, "Blogs/001/")).then((snapshot)=>{
if(snapshot.exists()){
var val = snapshot.val().Clicks;
update(ref(db, "Blogs/001"),{
Clicks: Number(val) + 1,
})
.then(()=>{
alert("data enter successful");
})
.catch((error)=>{
alert("unsuccessful, error="+error);
});
}
else{
alert("No data found");
}
})
.catch((error)=>{
alert("unsuccessful, error="+error);
});
}
Updates
I instead created a HTML button to work with my function and removed the link "" tags. I used the window.open() to open the link.
<button id="linkcntrbtn"> UPDATE </button>
Here's the JS function snippet
function LinkCounterButton() {
const dbref = ref(db);
get(child(dbref, "Blogs/001/")).then((snapshot)=>{
if(snapshot.exists()){
clicksbox.value = Number(snapshot.val().Link01Count) + 1;
var val = snapshot.val().Link01Count;
update(ref(db, "Blogs/001"),{
Link01Count: Number(val) + 1,
})
.catch((error)=>{
alert("unsuccessful, error="+error);
});
window.open("https://www.google.com", "_parent");
}
else{
alert("No data found");
}
})
.catch((error)=>{
alert("unsuccessful, error="+error);
});
return true;
}
linkcntrbtn.addEventListener('click', LinkCounterButton);
update(ref(db, "Articles/001/"),{
, but the screenshot shows (and the code *reads): from/Blogs/001
. Are those supposed t be the same?