Search code examples
jqueryhtmlpage-refresh

Maximum download counts -> then refresh page


I have a download page with a maximum download count of 5 for each file. Every download is linking to download.php?fileid. When clicked, the number of downloads is substracted with one in the database. But it's only updated when a visitor refreshes the page.

Now, I thought jQuery will help me out, and I have this now:

<span class="downloadsleft">5</span><span class="downloadLink">download file</span>

My jquery:

<script type="text/javascript">     
                $('.downloadLink').click(function() {

                        var currentValue = $(".amount").text();
                        var newValue = +currentValue - 1;

                        $(".amount").text(newValue);

                        window.open("download.php?file={/literal}{$product.bestandsnaam_hash}{literal}");                   

                        if ((".amount").text == "1")
                        {
                            location.reload();
                        };
                });  

            </script>

The window open works, but the reload doesn't work? Does anyone know this problem?


Solution

  • Explanation

    .amount isn't the good class name! use .downloadsleft instead!

    Since .amount does not exist, there is no initial value set to the variable currentValue.


    Solution

    (JSFiddle)

    Replace all the .amount in your JavaScript code by .downloadsleft:

    NOTE: I also added a parseInt() function in base10 to compare the number of downloads to a number.

    JavaSript/jQuery

      $('.downloadLink').click(function() {
          var currentValue = $(".downloadsleft").text();
          var newValue = currentValue - 1;
    
          $(".downloadsleft").text(newValue);
    
          window.open("download.php?file={/literal}{$product.bestandsnaam_hash}{literal}");                
    
          if (parseInt(newValue,10) == 1)
          {
              location.reload();
          };
      });