user3051125
user3051125

Reputation: 19

Overwriting a simple click count permanently using AJAX and PHP

I'm coding a site where, when any user clicks a button, a click counter increases and displays. The count must be permanently increased. The solution I imagine will involve some form of interaction between JS and PHP.

I'm completely familiar with JavaScript and jQuery, far less so with PHP. The fiddle here is useless beyond its showing the concept. It obviously refreshes back to 0 with each page load. I'd need to track and save the current clickCounter "worldwide", so to speak.

var clickCounter = 0;

$(document).ready(function () {
    $("#displayClicks").html("<h1>" + clickCounter + "</h1>");
    $("#button").click(function () {
        clickCounter++;
        $("#displayClicks").html("<h1>" + clickCounter + "</h1>");
    });
});

Upvotes: 1

Views: 1485

Answers (2)

Quin Schurman
Quin Schurman

Reputation: 118

In order to have the counter show a permanent value, you would have to store the value either in a static file or in a database.

Static File Method

When a user navigates to the counter page, you are going to have to have an AJAX call to a PHP script that grabs the current counter number.

If you are using a static file to store your counter number, you could simply send a request to the counter file to grab its contents instead of lengthening the process and having a PHP script do it.

Getting the Counter Value

JavaScript:

var counterValue = 0;

$(document).ready(function () {
    $.ajax({
        url: "Counter.txt",
        async: false,
        success: function (data){
            // This is assuming that Counter.txt's value will always be a number.
            counterValue = parseInt(data);
        }
    });
    $("#clickCount").html("<h1>" + counterValue + "</h1>");
    $("#clickThis").click(function () {
        $.ajax({
            url: "addcounter.php",
            success: function (){counterValue++;}
        });
        $("#clickCount").html("<h1>" + counterValue + "</h1>");
    });
});

Counter.txt's content could simply be 42.

Setting the Counter Value

PHP (addcounter.php):

$counterFile = "Counter.txt";
#               ^ the file we need to open is Counter.txt

$fileRW = fopen($counterFile, 'a');
#         ^ open the file

$fileContents = fread($fileRW, filesize($counterFile));
#               ^ get the contents of the file,
#                 so we know what to add to

$counterValue = intval($fileContents);

fclose($fileRW);
# ^ we close the file here so we can open again with the the 'w' mode,
#   which will truncate the file so we can rewrite its contents

$fileRW = fopen($counterFile, 'w');

fwrite($fileRW, $counterValue);
fclose($fileRW);
# ^ write to file and close

Database Method

If you choose to use this method, you would have to use a PHP script to get and set the counter value.

Getting the Counter Value

JavaScript:

var counterValue = 0;

$(document).ready(function () {
    $.ajax({
        url: "getcounter.php",
        async: false,
        success: function (data){
            // getcounter.php should always return a single number.
            counterValue = parseInt(data);
        }
    });
    $("#clickCount").html("<h1>" + counterValue + "</h1>");
    $("#clickThis").click(function () {
        $.ajax({
            url: "addcounter.php",
            success: function (){counterValue++;}
        });
        $("#clickCount").html("<h1>" + counterValue + "</h1>");
    });
});

PHP (getcounter.php):

$db_user        = "example";
#                 ^ replace with database login username

$db_pass        = "example";
#                 ^ replace with database login password

$db_info        = "mysql:host=localhost;dbname=example";
#               replace with: ^ host           ^ database name

$PDO = new PDO($db_info, $db_user, $db_pass);
#          ^ creates a connection to the MySQL database

$SQLQuery = "SELECT `counter` FROM `Counter`";
#                   ^ counter column      ^ counter table 

$Statement = $PDO->prepare($SQLQuery);
#                  ^ prepares a statement object from the query string
$Statement->execute();
$CounterData = $Statement->fetch();
#                          ^ fetches the info for the counter column in the Counter table

echo $CounterData['counter'];
#    ^ echo the counter value for the AJAX request

Setting the Counter Value

PHP (addcounter.php):

$db_user        = "example";
#                 ^ replace with database login username

$db_pass        = "example";
#                 ^ replace with database login password

$db_info        = "mysql:host=localhost;dbname=example";
#               replace with: ^ host           ^ database name

$PDO = new PDO($db_info, $db_user, $db_pass);
#          ^ creates a connection to the MySQL database

$SQLQuery = "UPDATE `Counter` SET `counter`=`counter`+1";
#                   ^ counter table     ^ set counter column to current value plus one 

$Statement = $PDO->prepare($SQLQuery);
#                  ^ prepares a statement object from the query string
$Statement->execute();

My knowledge of AJAX & JS is a bit rusty so please forgive any mistakes; this post was meant to summarize the code involved and isn't really meant for copy/paste.

Upvotes: 3

Tengiz
Tengiz

Reputation: 1920

Use Redis database or Memcached depends on how long you need to store that value. Each click on that button you send an ajax request to your server and increment your key.

Upvotes: 0

Related Questions