Jump to content

Recommended Posts

I am trying to make a counter in my web page in wordpress.

I have a button "lees" and when you hover over and then go of it must make a count for it.

 

The php code I have is working, but take long before it shows new count to show up.

 

function register_hover_count_endpoints() {
    register_rest_route('hover-count/v1', '/update', array(
        'methods' => 'POST',
        'callback' => 'update_hover_count',
    ));
    register_rest_route('hover-count/v1', '/get', array(
        'methods' => 'GET',
        'callback' => 'get_hover_counts',
    ));
}
add_action('rest_api_init', 'register_hover_count_endpoints');
function update_hover_count(WP_REST_Request $request) {
    $reset = $request->get_param('reset');
    $hover_counts = get_option('hover_counts', array());

    if ($reset) {
        $hover_counts = array();
        update_option('hover_counts', $hover_counts);
        return new WP_REST_Response('Hover counts reset', 200);
    }

    $index = $request->get_param('index');
    if ($index === null) {
        return new WP_REST_Response('Index parameter is required', 400);
    }
    
    if (!isset($hover_counts[$index])) {
        $hover_counts[$index] = 0;
    }
    $hover_counts[$index]++;

    if (update_option('hover_counts', $hover_counts)) {
        return new WP_REST_Response('Hover count updated', 200);
    } else {
        return new WP_REST_Response('Failed to update hover count', 500);
    }
}
function get_hover_counts() {
    $hover_counts = get_option('hover_counts', array());
    return new WP_REST_Response($hover_counts, 200);
}

java script

 

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('search-input').value = '';
  if (window.location.pathname.includes('besigheid')) {
    document.querySelectorAll('.lees-btn').forEach((button, index) => {
      button.addEventListener('mouseover', () => {
        fetch('/wp-json/hover-count/v1/update', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ index })
        }).then(response => {
          if (!response.ok) {
            console.error('Failed to update hover count');
          }
        }).catch(error => {
          console.error('Error:', error);
        });
      });
    });

    function updateAdminSection() {
      fetch('/wp-json/hover-count/v1/get')
        .then(response => response.json())
        .then(hoverCounts => {
          const hoverCountsList = document.getElementById('hover-counts');
          hoverCountsList.innerHTML = '';
          document.querySelectorAll('.business-card').forEach((card, index) => {
            // Changed from h2 to h3
            const businessName = card.querySelector('h3').textContent;
            const count = hoverCounts[index] || 0;
            const listItem = document.createElement('li');
            listItem.textContent = `${businessName}: ${count} hovers`;
            hoverCountsList.appendChild(listItem);
          });
        }).catch(error => {
          console.error('Error:', error);
        });
    }

    document.getElementById('submit-button').addEventListener('click', function(event) {
      event.preventDefault();
      const searchTerm = document.getElementById('search-input').value;
      console.log('Search term:', searchTerm);
      const enteredPassword = document.getElementById('admin-password').value;
      if (enteredPassword === 'Melandri@16Zandri@05') {
        updateAdminSection();
        document.getElementById('admin-password').style.display = 'none';
        document.getElementById('submit-button').style.display = 'none';
        document.getElementById('update-button').style.display = 'block';
        document.getElementById('reset-button').style.display = 'block';
      } else {
        alert('Wagwoord Verkeerd, Probeer weer asseblief.');
      }
    });

    document.getElementById('update-button').addEventListener('click', () => {
      updateAdminSection();
    });

    document.getElementById('reset-button').addEventListener('click', () => {
      fetch('/wp-json/hover-count/v1/update', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ reset: true })
      }).then(response => {
        if (!response.ok) {
          console.error('Failed to reset hover count');
          return;
        }
        return response.json();
      }).then(data => {
        console.log('Reset response:', data);
        localStorage.removeItem('hoverCounts');
        updateAdminSection();
        // Changed from h2 to h3 here as well
        document.querySelectorAll('.business-card').forEach((card) => {
          const listItem = card.querySelector('li');
          if (listItem) {
            listItem.textContent = `${card.querySelector('h3').textContent}: 0 hovers`;
          }
        });
      }).catch(error => {
        console.error('Error:', error);
      });
    });

    const toggleButton = document.getElementById('toggle-button');
    const adminSection = document.getElementById('admin-section');

    toggleButton.addEventListener('click', function() {
      if (adminSection.style.display === 'none' || adminSection.style.display === '') {
        adminSection.style.display = 'block';
      } else {
        adminSection.style.display = 'none';
      }
    });

    document.getElementById('search-button').addEventListener('click', function(event) {
      event.preventDefault();
      console.log('Search functionality should be implemented here');
      const searchTerm = document.getElementById('search-input').value;
      console.log('Search term:', searchTerm);
    });
  }

 

On 2/11/2025 at 3:04 PM, hendrikbez said:

I am trying to make a counter in my web page in wordpress.

I have a button "lees" and when you hover over and then go of it must make a count for it.

 

The php code I have is working, but take long before it shows new count to show up.

 

function register_hover_count_endpoints() {
    register_rest_route('hover-count/v1', '/update', array(
        'methods' => 'POST',
        'callback' => 'update_hover_count',
    ));
    register_rest_route('hover-count/v1', '/get', array(
        'methods' => 'GET',
        'callback' => 'get_hover_counts',
    ));
}
add_action('rest_api_init', 'register_hover_count_endpoints');
function update_hover_count(WP_REST_Request $request) {
    $reset = $request->get_param('reset');
    $hover_counts = get_option('hover_counts', array());

    if ($reset) {
        $hover_counts = array();
        update_option('hover_counts', $hover_counts);
        return new WP_REST_Response('Hover counts reset', 200);
    }

    $index = $request->get_param('index');
    if ($index === null) {
        return new WP_REST_Response('Index parameter is required', 400);
    }
    
    if (!isset($hover_counts[$index])) {
        $hover_counts[$index] = 0;
    }
    $hover_counts[$index]++;

    if (update_option('hover_counts', $hover_counts)) {
        return new WP_REST_Response('Hover count updated', 200);
    } else {
        return new WP_REST_Response('Failed to update hover count', 500);
    }
}
function get_hover_counts() {
    $hover_counts = get_option('hover_counts', array());
    return new WP_REST_Response($hover_counts, 200);
}

java script

 

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('search-input').value = '';
  if (window.location.pathname.includes('besigheid')) {
    document.querySelectorAll('.lees-btn').forEach((button, index) => {
      button.addEventListener('mouseover', () => {
        fetch('/wp-json/hover-count/v1/update', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ index })
        }).then(response => {
          if (!response.ok) {
            console.error('Failed to update hover count');
          }
        }).catch(error => {
          console.error('Error:', error);
        });
      });
    });

    function updateAdminSection() {
      fetch('/wp-json/hover-count/v1/get')
        .then(response => response.json())
        .then(hoverCounts => {
          const hoverCountsList = document.getElementById('hover-counts');
          hoverCountsList.innerHTML = '';
          document.querySelectorAll('.business-card').forEach((card, index) => {
            // Changed from h2 to h3
            const businessName = card.querySelector('h3').textContent;
            const count = hoverCounts[index] || 0;
            const listItem = document.createElement('li');
            listItem.textContent = `${businessName}: ${count} hovers`;
            hoverCountsList.appendChild(listItem);
          });
        }).catch(error => {
          console.error('Error:', error);
        });
    }

    document.getElementById('submit-button').addEventListener('click', function(event) {
      event.preventDefault();
      const searchTerm = document.getElementById('search-input').value;
      console.log('Search term:', searchTerm);
      const enteredPassword = document.getElementById('admin-password').value;
      if (enteredPassword === 'Melandri@16Zandri@05') {
        updateAdminSection();
        document.getElementById('admin-password').style.display = 'none';
        document.getElementById('submit-button').style.display = 'none';
        document.getElementById('update-button').style.display = 'block';
        document.getElementById('reset-button').style.display = 'block';
      } else {
        alert('Wagwoord Verkeerd, Probeer weer asseblief.');
      }
    });

    document.getElementById('update-button').addEventListener('click', () => {
      updateAdminSection();
    });

    document.getElementById('reset-button').addEventListener('click', () => {
      fetch('/wp-json/hover-count/v1/update', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ reset: true })
      }).then(response => {
        if (!response.ok) {
          console.error('Failed to reset hover count');
          return;
        }
        return response.json();
      }).then(data => {
        console.log('Reset response:', data);
        localStorage.removeItem('hoverCounts');
        updateAdminSection();
        // Changed from h2 to h3 here as well
        document.querySelectorAll('.business-card').forEach((card) => {
          const listItem = card.querySelector('li');
          if (listItem) {
            listItem.textContent = `${card.querySelector('h3').textContent}: 0 hovers`;
          }
        });
      }).catch(error => {
        console.error('Error:', error);
      });
    });

    const toggleButton = document.getElementById('toggle-button');
    const adminSection = document.getElementById('admin-section');

    toggleButton.addEventListener('click', function() {
      if (adminSection.style.display === 'none' || adminSection.style.display === '') {
        adminSection.style.display = 'block';
      } else {
        adminSection.style.display = 'none';
      }
    });

    document.getElementById('search-button').addEventListener('click', function(event) {
      event.preventDefault();
      console.log('Search functionality should be implemented here');
      const searchTerm = document.getElementById('search-input').value;
      console.log('Search term:', searchTerm);
    });
  }

 

There could be many reasons for this to happen. It sounds to me like server processing time or network latency.

You could try implementing a debounce function to limit the number of requests sent to the server when the user hovers over the button multiple times in quick succession.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.