Increasing counter on button click and save that counter

angularjs
#1

Hi,
I want to create button, that if someone clicks it should show how many times it clicked, also when other person comes to that page it should start from last clicked number and when he clicks that number should increase from last clicked number.
eg. 1st person clicked button 10 times and at that time counter is started from 0.
Result after last click: 10

  2nd person clicked button 5 times at that time counter starts from 10.
   Result after last click: 15

Please refer this link

0 Likes

#2

Hi @msupriyarhyzome, that plunker you have linked uses angularJS – this is a legacy framework and shouldn’t be used for new projects any more. As for having all users visiting the page see the same number, this can only be achieved by storing the current number in a backend database; and whenever someone clicks the button, you’d send a request to the server to increment the number using AJAX, and in turn receive the updated number. The frontend part might look something like this (using the fetch API here):

const increment = document.getElementById('increment')
const counter = document.getElementById('counter')

increment.addEventListener('click', () => {
  increment.disabled = true

  fetch('./increment.php')
    .then(response => response.text())
    .then(count => {
      counter.textContent = count
    })
    .catch(error => {
      counter.textContent = error
    })
    .finally(() => {
      increment.disabled = false
    })
})
2 Likes

#3

Hi @m3g4p0p,
Thank you so much for the help. :smiley:
Actually I want to add this feature in my wordpress site, can you help me with the procedure to be done for that?
It would be great if you can.

Thank you.

0 Likes

#4

Oh hm… I think there are basically 2 approaches then:

  • If the counter is related to a specific post or page, add the counter value as post meta
  • If the counter should share its value across multiple posts or pages, write a plugin that creates its own database table

In both cases you’ll need to register a custom endpoint in the REST API for your AJAX requests… if you need help with this I’d suggest to start a new topic over in the CMS & WP category.

(Another option might be checking if there are plugins for this – there certainly are --, but you know how that goes… before you know you have like 5 additional plugins installed and your setup becomes an unmaintainable mess.) :-|

0 Likes

closed #5

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.

0 Likes