Hi all! I need a script in javascript which is counting how many times a button was pressed and stores the count in a text file. Can anyone help me please? Thank you all!
@Jarrod1937Nov 29.2011 — #Why a text file? If you want the text file server side you'll need to use a server side language as well and use AJAX techniques, if you want to store a text file locally on the users computer... well good luck with that because of security concerns. However, locally you can store that info via a cookie, which will work the same.
@CuCauthorNov 29.2011 — #Ok, I understand. The idea is that I want every time when a visitor pressed a button to be counted and the count number to be displayed on the homepage. If you have an idea how can I make that easier please help me!
@Jarrod1937Nov 29.2011 — #Do the buttons go to a predictable page? Are those pages run by a server side script (like PHP)? If so, then an easier method would be to just count the page accesses, which would be the equivalent, unless you're wanting to track traffic from a specific path (aka the buttons only). That would be easier as all you'd need is:
[code=php] <?php $pageid=3; // database access stuff here, or text file access // for a database its as easy as mysql_query("UPDATE counter set countval=countval+1 WHERE pageval='".(int)$pageid."' ");
// The countval is the counter value, and the pageval is the page you're viewing // For a text file it's basically as easy as grabbing the value recorded in the file // casting it to an int, incrementing it by 1, and then recording that value back.
@007JulienNov 29.2011 — #You have, a first, to define a variable (for example [I]counter[/I]) and to give it the value 0.
Than display an a onclick on the button to call a function which increment the counter and display its value... [code=html]<script type="text/javascript"> var counter=0; function clc(){ counter++; document.getElementById('spc').innerHTML=counter; } </script> <body> <p>You clicked <span is="spc">0</span> times on the button.</p> <input type="button" value="Click me !" onclick="clc()"> </body>[/code]
@Jarrod1937Nov 29.2011 — #007Juliens method will work, though i assumed you wanted a permanent counter that counts how many people have went to that page that the button links to. If you just need a a temporary counter that counts how many times a single user has clicked a button 007's method will work and is much simpler... though if that is the case then it sounds like we're doing your homework for you...
@JunkMaleNov 29.2011 — #If your counting then with each button click, it adds its own ID value to the URL which is passed between pages so that the users clicks can be tracked across the site and counted on the subsequent page load.
Then you can use a database to store the information that is also accessed to place an accurate click counter on the page or give your site a button click listing of what is clicked.