I have a problem when trying to count in PHP using a button and a text file to save it. I can’t see the problem in my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="p">Click here</div>
<div id="results"></div>
<script>
$('#p').click(function()
{
$('#results').load("count.php");
});
</script>
</body>
</html>
count.php contains the following:
<?php
$clicks = file_get_contents("clicks.txt");
$clicks++;
$fp = fopen("clicks.txt", "w+");
fwrite($fp, $clicks);
fclose($fp);
//give the count to the user
echo "result: $clicks";
?>
From the OP it looks like you want this data to be retained and accumulate for all users, so a server side component is necessary.
Here is my take on it:
HTML
PHP
notice the php is the same but I now change the $clicks value to an integer after I get it from the file.
You also need to ensure the files are read/write for the server… in linux you would just do this:
to make your
www/directory (or change it to the directory your Apache(?) server uses..) read/writeable by the server (this may be overkill, you can target specific files using the same method, just remove the-R(recursive) flag).I tested this setup locally and it works for me, goodluck!
Edit: Just being nice….
Here is a no-jQuery solution to the JS (this won’t work in all browsers, specifically older IE versions, I’ll let you handle these 😛 )
Live Demo
Ignore the add code that gets spit back out from the server…. damn free hosts