Button click counter save number

前端 未结 2 1572
花落未央
花落未央 2020-12-18 15:53

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

This is the code:

相关标签:
2条回答
  • 2020-12-18 16:25

    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>
    
    0 讨论(0)
  • 2020-12-18 16:42

    You need a DB connection to do this.

    When the button is clicked, by any user, the value from let's say: "downloaded_times" will be increased with 1.

    so you will need a query like:

    UPDATE table SET downloaded_times = downloaded_times + 1

    this query will be called each time someone presses the button.

    If you want to display it, before a certain user wants to start a download, you simply fetch the result from DB and the echo it. You can do more, if you want that field to be constantly refreshed, the fetching and echoing part should be in a ajax called PHP function, that will refresh the div (for instance) every 30 second or so :D

    Hope this helps! :D

    0 讨论(0)
提交回复
热议问题