I simply just want to count the clicks of a button and save the amount of clicks to a text file, but I cannot seem to get this code to work. It does not save the amount of clicks.
In the HTML file I have a button that runs the JavaScript using onClick:
function do() {
if (window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}
else
{
if (window.ActiveXObject){
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xhr.open('GET','count.php',false);
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 && xhr.status === 200 ) {
while(results.hasChildNodes()) {
results.removeChild(results.lastChild);
}
results.appendChild(document.createTextNode(xhr.responseText));
}
}
xhr.send();
}
In the PHP file we called, we have the following code:
<?php
$clicks = file_get_contents("clicks.txt");
$clicks++;
$fp = fopen("clicks.txt", "w+");
while ( !flock($fp, LOCK_EX) ) {
usleep(500000); // Delay half a second
}
fwrite($fp, $clicks);
fclose($fp);
flock($fp, LOCK_UN);
?>
Can you help me to find the problem in my code?
How would I read the text file in another HTML page?
(Just show the information of the text file.)
xhr = new XMLHttpRequest()should be used, the actual request tocount.phpis never executed because the relevant code is only present in the scope ofelse. Move the remaining code outside theifstatement