46282

Saving the click count of multiple buttons to file using AJAX and PHP

Question:

I have some code which is working just fine counting the number of clicks of a single button. However I don't know how to let it count multiple buttons for me.

How should I extend my code to count clicks from other buttons?

PHP script:

<?php $counterFile = 'counter.txt' ; if (isset($_GET['increase'])) { if (($counter = @file_get_contents($counterFile) ) === false ) { die('Error : file counter does not exist'); } file_put_contents($counterFile,++$counter) ; echo $counter ; return false ; } if (!$counter = @file_get_contents($counterFile)) { if (!$myfile = fopen($counterFile,'w')) { die('Unable to create counter file !!') ; } chmod($counterFile,0644); file_put_contents($counterFile,0) ; } ?>

Javascript:

$('#download1').on('click',function(){ jQuery('div#counter').html('Loading...') ; var ajax = jQuery.ajax({ method : 'get', url : '/test.php', // Link to this page data : { 'increase' : '1' } }) ; ajax.done(function(data){ jQuery('div#counter').html(data) ; }) ; ajax.fail(function(data){ alert('ajax fail : url of ajax request is not reachable') ; }) ; });

Answer1:

To clear things up I've split my answer into three parts (PHP, JS and HTML) so you can see how it works.

<h3>PHP</h3> $counterFile = 'counter.txt'; if (isset($_GET['increase'])) { if (($counters = unserialize(@file_get_contents($counterFile))) === false) { die('Error : file counter does not exist'); } switch ($_GET['counter']) { case 'counter_one': $counters['counter_one'] += $_GET['increase']; break; case 'counter_two': $counters['counter_two'] += $_GET['increase']; break; } file_put_contents($counterFile, serialize($counters)) ; foreach ($counters as $name => $count) { echo $name.": ".$count."<br />"; } exit; } if (!$counters = unserialize()@file_get_contents($counterFile)) { if (!$myfile = fopen($counterFile,'w')) { die('Unable to create counters file'); } chmod($counterFile,0644); file_put_contents($counterFile, serialize(array('counter_one' => 0, 'counter_two' => 0))); } <h3>Javascript</h3> $(document).ready(function ($) { $(document).on('click', '.counter', function() { var counter = $(this).data('counter'); jQuery('div#counter').html('Loading...') ; var ajax = jQuery.ajax({ method : 'get', url : '/test.php', // Link to this page data : { 'increase' : '1', 'counter': counter } }) ; ajax.done(function(data){ jQuery('div#counter').html(data); }); ajax.fail(function(data){ alert('ajax fail : url of ajax request is not reachable') ; }); }); }); <h3>HTML</h3>

Simply add a data attribute to your buttons.

<button class="counter" data-counter="counter_one">Click me</button> <button class="counter" data-counter="counter_two">Click me</button>

Answer2:

Send the button ID to the server script, and store an associative array in the file in JSON format.

PHP:

<?php $counterFile = 'counter.json' ; if ( isset($_GET['increase'], $_GET['button']) ) { $button_name = $_GET['button']; if ( ( $counter = @file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ; $count_array = json_decode($counter, true); $count_array[$button_name] = isset($count_array[$button_name]) ? $count_array[$button_name] + 1 : 1; file_put_contents($counterFile, json_encode($count_array)) ; echo $count_array[$button_name] ; return false ; } if ( ! $counter = @file_get_contents($counterFile) ) { if ( ! $myfile = fopen($counterFile,'w') ) die('Unable to create counter file !!') ; chmod($counterFile,0644); file_put_contents($counterFile, json_encode(array())) ; } ?>

JS:

$('.download').on('click',function(){ jQuery('div#counter').html('Loading...') ; var ajax = jQuery.ajax({ method : 'get', url : '/test.php', // Link to this page data : { 'increase' : '1', button: this.id } }) ; ajax.done(function(data){ jQuery('div#counter').html(data) ; }) ; ajax.fail(function(data){ alert('ajax fail : url of ajax request is not reachable') ; }) ; }) ;

Answer3:

Your making this way harder than you need too. Just use a DB for this. You are already using AJAX so just call the DB with AJAX and count the clicks that way.

php script <strong>counterdownload1.php</strong>:

<? $sql = mysql_query("UPDATE download1 SET counter = counter+1"); ?>

ajax:

$('#download1').on('click',function(){ // blah blah your code $.ajax({ type: "POST", url: "counterdownload1.php" }); )};

Recommend

  • Content hiding above div's
  • PHP Last Object of Method Chaining
  • shell_exec('which git') returns empty string on Godaddy shared hosting server
  • How to configure PhpUnit in Xampp?
  • PDF in PHP ZipArchive throwing errors, server permissions
  • “cpanm PHP” fails
  • Zend Framework 2, Module Redirect
  • PHP Handling Namespace with SimpleXML
  • Check all commands exit code within a bash script
  • How do I prepend to a stream in Bash?
  • manupulating a string to create directories in unix
  • Getting syntax error in mysql-php. You have an error in your SQL syntax;
  • removing last 3 characters on a file (file extension)
  • Installing PHP 7 on digitalocean
  • Get specific string
  • How does this usort cmp function actually work?
  • Stop Bash Script if Hive Fails
  • How to add git credentials to the build so it would be able to be used within a shell code?
  • Why ng-show works with ng-repeat but ng-if doesn't? [duplicate]
  • HTML download movie download link
  • Updating server-side rendering client-side
  • Display Images one by one with next and previous functionality
  • Upload files with Ajax and Jquery
  • jquery mobile loadPage not working
  • Data Validation Drop Down Box Arrow Disappearing
  • How to set the response of a form post action to a iframe source?
  • Hits per day in Google Big Query
  • How do you join a server to an Active Directory (domain)?
  • how does django model after text[] in postgresql [duplicate]
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • Net Present Value in Excel for Grouped Recurring CF
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?