Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

javascript - Button click counter save number

I have this fiddle where when the user clicks a button the counter works: http://jsfiddle.net/z66WF/

This is the code:

<button type="button" onClick="clickME()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>

 var clicks = 0;
 function clickME() {
    clicks += 1;
    document.getElementById("clicks").innerHTML = clicks;
 }

The problem is that I want the number to be saved, so for example:

  1. user #1 clicks on the button 10 times
  2. user #2 opens the site and the count is at 10, he clicks and now the counter starts 11
  3. and so on with new users.

I'm trying to do this to keep track of how many times a file has been downloaded.

Any idea how can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you have a working simple exemple, wich write the counter in a simple txt file (no sql db needed)

<?php

    $counterFile = 'counter.txt' ;

    // jQuery ajax request is sent here
    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) ;
    }

?>
<html>
    <head>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
        <script type="text/javascript">
            jQuery(document).on('click','a#download',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') ;
                }) ;
            }) ;
        </script>
    </head>
    <div id="counter"><?php echo $counter ; ?></div>
    <a href="" id="download" onclick="window.open(this.href);return false;">Download btn</a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...