Click-o-Meter: Tracking Button Presses

I’m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet:

<?php

    $counterFile = 'path/to/counter.txt' ;

    // This is where the jQuery Ajax request is sent
    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) ;
            }

        ?>
         <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>
    <div id="counter"><?php echo $counter ; ?></div>
    <a href="<?php echo get_field("pdf"); ?>" id="download" onclick="window.open(this.href);return false;">Download Button</a>

The issue I'm facing is that when I click on the "Download Button," the PDF opens, but the counter disappears, and upon refreshing the page, it always shows as 0. Do you have any idea what might be causing this problem?

Answer №1

The page reload occurs when the link is clicked, as it still functions as a standard link.

To prevent this, you have two options:

    jQuery(document).on('click','a#download',function(){
        ...
        return false;
    });

Alternatively, you can use preventDefault() to stop the default action from occurring:

    jQuery(document).on('click','a#download',function(e){
        e.preventDefault()
        ...
    });

You are currently using both an onclick= attribute and a jQuery event handler on the same button, which is not ideal.

I recommend using only jQuery for the event handlers. For example:

    jQuery(document).on('click','a#download',function(e){
        e.preventDefault()
        window.open(this.href);
        ... Other code goes here ...
    });

Make sure to remove the

onclick="window.open(this.href);return false;"
attribute from the button.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interacting with iView UI dropdown menu items

I'm attempting to create a click event in iView ui. Here's my code: <DropdownMenu slot="list"> <DropdownItem @on-click="markAsRead">Mark as read</DropdownItem> </DropdownMenu> The function markAsRead isn't exec ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Collecting all the <td> elements within a single row

I am having trouble creating a table dynamically using JSON data. The issue is that all <td> elements are being placed in the same <tr> instead of two separate rows. Here is my JavaScript code: $('button').click(function() { var str ...

Flip the Script: JQuery slideshow in reverse

Hey there, I've been tinkering with a JQuery slideshow and encountering an issue. All my images in the HTML are stacked on top of each other, and I attempted to modify the code so it starts with the last image. However, my attempts have not been succe ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

Getting the value of a JavaScript variable and storing it in a Python variable within a Python-CGI script

Is there a way to capture the value of a JavaScript variable and store it in a Python variable? I have a Python-CGI script that generates a selection box where the user can choose an option from a list. I want to then take this selected value and save it ...

How can I convert a list of checkboxes, generated by ng-repeat, into multiple columns?

Here is the HTML code snippet: <div class="checkbox"> <label> <input type="checkbox" ng-model="selectedAll.value" ng-click="checkAll()" />Check All </label> </div> <div class="checkbox" ng-repeat="carType i ...

How can you extract a JSON object from a JSON array based on a key that is associated with a specific JSON

Is it possible to retrieve a specific JSON object from an array of JSON objects based on a condition? [ { id: 1, name: "larry" }, { id: 2, name: "curly" }, { id: 3, name: "moe" } ] For example, if I want to extract the object where name is equal to " ...

Is there a way to efficiently clear the Express session for all users without the need to restart the application?

During my development of REST services using the nodejs express framework, I encountered an issue with storing user-specific data in sessions. I utilized the user's ID as a key to identify the user's data. The following code snippet demonstrates ...

Vue - Unable to navigate to a different route

I just started working with Vue and attempted to redirect '/home' to '/travel', but for some reason it's not functioning correctly. Can someone please guide me on how to achieve this? What could be the issue with my code? Thank y ...

iCheck jQuery Callback

I'm using Jquery iCheck to style input fields and I have encountered a problem with handling the callback from iCheck. What I need is to retrieve all checked input values within a container that has a specific class name. http://jsfiddle.net/lgtsfidd ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

Exploring the combination of Express router, Auth0, and plain Javascript: A guide to implementing post-login authentication on a router

After creating a front end with vite using vanilla javascript and setting up a backend with node.js express routes, I successfully integrated swagger for testing purposes. I have managed to enable functionalities such as logging in, logging out, and securi ...

Encountering Issues with Ajax Request in the Google Play App

I am facing an issue with my Phonegap app. It functions perfectly in debug mode and when installed as an apk file from Phonegap. However, when I upload it to Google Play Store and then download it from there, my ajax requests stop working. I have added the ...

What is the best way to retrieve the current value of a range slider?

Having some trouble with the "angular-ranger" directive that I loaded from a repository. Can anyone assist me in figuring out how to retrieve the current value of the range slider? Any guidance or suggestions would be greatly appreciated! For reference, ...

Toggle the visibility of an element using a checkbox in JavaScript

In my scenario, there are 8 checkboxes where only one is checked by default. If you click on the unchecked checkboxes twice, the table linked to them will hide. Ideally, I want the unchecked checkboxes to be hidden by default and the checked one to be sh ...