user3552910
user3552910

Reputation:

How to make a click counter where the value doesn't reset

I need to make a click counter where the value doesn't reset when the page is refreshed. I also need it to be a culmination of all clicks from all users, not just one user. So it will, essentially, be one big click counter. Here is my code, but I don't have a great idea of what I am doing.

    <!DOCTYPEhtml>
 <html>
 <head>
 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
 </head>
 <body>
 Clicks:<span id="numClicked"></span><br>
 <button id="button">Click</button>
 </body>
 </html>
 <script type="text/javascript">
 $('#button').click(function(){

       $.ajax({
          url: "saveCounter.php",
          type: "POST",
          data: {
             "action" : "increment"
          }
         }).success(function(data){
              $('#numClicked').html(data);
         }).error(function(){

         });

       });

    $(document).ready(function() {
      $.ajax({
          url: "saveCounter.php",
          type: "POST",
          data: {
             "action" : "get"
          }
       }).success(function(data){

           $('#numClicked').html(data);

       }).error(function(){

       });

});
</script>
<?php
if (!isset(GLOBALS["value"])
{
  $GLOBALS["value"] = 0;
}

$action = filter_input(INPUT_POST, "action", FILTER_UNSAFE_RAW);

if ($action !== null)
{
  if ($action == "increment")
  {
     $GLOBALS["value"] += 1;
  }

  echo $GLOBALS["value"];

}
?>

Upvotes: 0

Views: 2771

Answers (3)

Orelsanpls
Orelsanpls

Reputation: 23545

You need to save the number of click value in your server or cookie

Soluce 1

  • Make AJAX request to save dynamically the amount of click on the server
  • Load the value saved before on the server

Javascript

    $('#buttonID').click(function(){

       $.ajax({
          url: "saveCounter.php",
          type: "POST",
          data: {
             "action" : "increment"
          }
         }).success(function(data){
              $('#numberOfClickContainerID').html(data);
         }).error(function(){

         });

       });

    $(document).ready(function() {
      $.ajax({
          url: "saveCounter.php",
          type: "POST",
          data: {
             "action" : "get"
          }
       }).success(function(data){

           $('#numberOfClickContainerID').html(data);

       }).error(function(){

       });

});

php

if (!isset(GLOBALS["value"])
{
  $GLOBALS["value"] = 0;
}

$action = filter_input(INPUT_POST, "action", FILTER_UNSAFE_RAW);

if ($action !== null)
{
  if ($action == "increment")
  {
     $GLOBALS["value"] += 1;
  }

  echo $GLOBALS["value"];

}

How everything is working?

  • At the page loading ($(document).ready()) we call dynamically a php page name saveCounter.php with specific arguments in purpose to get the saved amount of click available on the server.
  • We assicioted some action to the button click. When the user click, we call dynamically saveCounter.php to increment the counter value and retrieve the new one.

Soluce 2

  • Use cookie according to this tutorial

Upvotes: 0

user2660757
user2660757

Reputation: 11

You can use html5 localStorage.

This similar example is on the w3's webpage: http://www.w3schools.com/html/html5_webstorage.asp

 function onClick() { 
    if (localStorage.hasOwnProperty('clicks')) {
        localStorage.clicks = Number(localStorage.clicks)+1;
    } else {
        localStorage.clicks = 0;
    }
    document.getElementById("clicks").innerHTML = localStorage.clicks;
 };

Upvotes: 0

Nile
Nile

Reputation: 1586

Since you have only tagged javascript and html, I will assume you want to do this using pure javascript, and you do not have access to a server language or storage to implement this. Since you are just tracking clicks, this may be a viable solution. If so, you can use localStorage, which will allow you to store a little bit of information in the user's browser so that it will be retained across refresh and browser sessions; however, the user can clear this value if they know how and their count will reset.

Demo: http://jsfiddle.net/f5VG8/6/

HTML:

<button type="button" id="clickButton">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>

Javascript:

var clicks = 0;

function initiateClicks() {
    var clickStr = localStorage.getItem("clicks");
    if(clickStr == undefined){
        localStorage.setItem("clicks", 0);
        clicks = 0;
    }else{
        clicks = parseInt(clickStr);   
    }
    document.getElementById("clicks").innerHTML = clicks;
}

function doClick() {
    clicks += 1;
    localStorage.setItem("clicks", clicks);
    document.getElementById("clicks").innerHTML = clicks;
}

document.getElementById("clickButton").onclick = doClick;
initiateClicks();

What this is doing is loading the click value from the user's browser when the page loads, and writing to it every time that the user clicks. When the user refreshes or exits their browser and then revisits your page later, their click count will be retained provided that the user do not clear the localStorage value you have set. In addition, I believe that localStorage will only work in modern browsers.

Try it: http://jsfiddle.net/f5VG8/6/

Upvotes: 4

Related Questions