0

I'm sure this is a super easy fix and I just can't see it.. I have a play button and I only want it to write to database (inc playcount) only when it's clicked the first time.

Any idea why this doesn't work? This result counts every click, and if I do if countonce = 0 and declare at beginning as 0 it won't count any clicks. Am I misunderstanding javascript?

 <div id="left-05-play_">
 <script type="text/javascript">
 var currsong = 1;
 var playcountadd = document.getElementById('left-05-play_');
 playcountadd.onclick = function() {
 if (countonce != 1) {
 $.post( "php/songadd.php", { addsong: "1", } );
 var countonce = 1;
 } }
 </script>
 </div>

Thank-you for taking the time to read this question.

3
  • 4
    move the var out of the function Commented Oct 7, 2014 at 6:34
  • I appreciate your comment, thank-you Commented Oct 7, 2014 at 6:43
  • i would also disable the button in the onclick to indicate to the user that further clicks will be ignored even with internet working. Commented Oct 7, 2014 at 6:45

1 Answer 1

1

This should do the trick.

var currsong = 1;
var songadded = false;
var playcountadd = document.getElementById('left-05-play_');

playcountadd.onclick = function() {
   if (!songadded) {
      $.post( "php/songadd.php", { addsong: "1", } );
      songadded = true;
   }
}
  • Changed countonce to songadded
  • Moved songadded out of onclick function
  • Changed songadded to boolean logic
  • Check whether songadded=false before proceeding with AJAX post
Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you so much curt! Worked beautifully of course and showed me something extremely valuable, can't thank-you enough!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.