I try to pass the current page URL (window.location.href
) with pure javascript Ajax to the php variable$_REQUEST['url']
. what am I doing wrong?
Counter.js:
'use strict';
let clicks = document.querySelectorAll('.Counter-trigger'); // IE8
let voted = localStorage.getItem('voted');
let message = document.getElementById('Counter-message');
let count = document.getElementById('Counter-count');
let i;
let url;
let post;
let xhr;
for (let i = 0; i < clicks.length; i++) {
clicks[i].onclick = function () {
if (voted == 'voted') {
message.innerHTML = "Sorry, ...!!";
} else {
let url = window.location.href;
let post = url; // post string
let xhr = new XMLHttpRequest();
xhr.open('POST', './lib/Counter/CounterReq.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200) return;
console.log(xhr.responseText);
message.innerHTML = "Thanks!!";
count.innerHTML = +count.textContent+1;
};
xhr.send(post);
localStorage.setItem('rate', 'voted');
voted = 'voted';
}
}
}
CounterReq.php
$url = $_GET['url']; // posted from page
$origin = $_SERVER['DOCUMENT_ROOT'].parse_url($url,PHP_URL_PATH);
$file = '_Counter.txt'; // counts is saved in this document
$file_path = $origin.'_Counter.txt'; // counts is saved here
$count = file_get_contents($file_path);
if ($count == null){$count = 0; echo $count;
}
$count++; // increment count by 1
$handle = fopen($file_path, "w+");
flock($handle,LOCK_EX); // LOCK_EX (2) exclusive locking for write access
fwrite($handle, $count);
flock($handle,LOCK_UN); // LOCK_EX (3) Releases a lock
fclose($handle); // close file
index.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/'.$_SERVER['REQUEST_URI']; // the path to the file
$file = '_Counter.txt'; // the number of vote is saved here
$file_path = $path.'_Counter.txt'; // the number of vote is saved here
if (!file_exists($file)) { // if the file does not exist, it will be created
fopen($file, "w"); } // open file for writing only
$count = file_get_contents($file_path); // reads entire file into a string
if ($count == null){$count = 0;} // if the file empty, set count 0
?>
<button class="Counter-trigger">vote</button>
<span id="Counter-count">'.$count.'</span> times<br>
<div id="ClapsCounter-message"></div>
<script async src="./lib/Counter/Counter.js"></script>
console.log:
Notice: Undefined index: url in /var/www/dist/lib/Counter/CounterReq.php on line 5