При нажатии кнопки Like/Dislike увеличить счётчик, а при повторном нажатии - вернуть в исходное состояние
Есть рабочий пример оценки комментариев. Все работает (нажимаешь Like- плюс 1, нажимаешь Dislike - минус 1). Только как вернуть все в исходное состояние при повторном нажатии кнопки?
<?
// Checking the id of the evaluated comment received via javascript
if (isset($_POST["comm_id"]) and is_numeric($_POST["comm_id"]))
$obj = $_POST["comm_id"];
else $obj = '';
// Checking the "rate" sent via JS with a value of 1
if (isset($_POST["rate"]) and ($_POST["rate"] == 0 or $_POST["rate"] == 1))
$rate = $_POST["rate"];
else $rate = '';
if ($rate != '' and $obj > 0) {
$rating_plus = 0;
$rating_minus = 0;
if ($rating_plus == 0 and $rating_minus == 0) {
if ($rate == 0) $rating_minus++;
else $rating_plus++;
}
else {
if ($rate == 0) {
$rating_minus++;
$rating_plus--;
} else {
$rating_minus--;
$rating_plus++;
}
}
//Calculating the rating of a comment
$sum = $rating_plus - $rating_minus;
if ($sum < 0) $color_sum = '#865656';
else {
$color_sum = '#688656';
if ($sum == 0) $color_sum = '#888';
}
$rating_sum = '<b style="color: '.$color_sum.'">'.$sum.'</b>';
// Forming a response
$output = ['rating_sum' => $rating_sum];
exit(json_encode($output));
}
//Calculating the rating of a comment
$sum = $Row["plus"] - $Row["minus"];
if ($sum < 0) $comm_rate = '<b style="color: #865656">'.$sum.'</b>';
else {
$comm_rate = '<b style="color: #688656">'.$sum.'</b>';
if ($sum == 0) $comm_rate = '<b style="color: #888">'.$sum.'</b>';
}
// --/-- //
$Row["id"] = 4;
$com_rating = '
<div class="rating_com">
<div class="comm_plus">Like</div>
<div class="comm_rate" id="rating_comm'.$Row["id"].'">
'.$comm_rate.'
</div>
<div class="comm_minus">Dislike</div>
</div>';
echo '
<div class="comments" id="m'.$Row["id"].'">
<div class="com_block">
<div class="name">$Name</div>
<div class="companel">
'.$com_rating.'
</div>
<p>$Row["text"]</p>
</div>';
?>
<script>
document.querySelectorAll('.comm_plus,.comm_minus,.comm_rate').forEach(arm =>{
arm.addEventListener('click', e => {
var id_comm = e.target.closest(".comments").getAttribute('id').substr(1); // we get the id of the rated comment and trim the first letter.
// Check if "comm_plus" was pressed, then the value "1" will be sent to $_POST['rate']
if (arm.classList.contains("comm_plus")) var num = 1;
if (arm.classList.contains("comm_minus")) var num = 0;
var xmlhttp = getXmlHttp();
xmlhttp.open('POST', '/news/material', true);
xmlhttp.responseType = 'json';
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(`rate=${num}&comm_id=` + encodeURIComponent(id_comm));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
const response = xmlhttp.response;
var com_rate = document.getElementById(`rating_comm`+id_comm);
com_rate.classList.add('_active');
setTimeout(() => {
com_rate.classList.remove('_active');
com_rate.innerHTML = `${response.rating_sum}`;
}, 500);
}
};
});
});
// The function creates an XMLHTTP object to send data to a POST request (without using an html form)
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp = new XMLHttpRequest();
return xmlhttp;
}
</script>
<style>
.comments {width: 60%; margin: 4em 2em; border: 2px solid grey; border-radius: 10px; padding: 1em}
.com_block .name {display: inline-block; margin: 0 0 7px;}
.com_block .companel {float: right; color: #6A6E68;}
.comment_edit {padding: 6px}
.comment_edit #button {margin-top: 4px}
.rating_com {margin: 0 5px 0 9px}
.rating_com div {display: inline-block}
.comm_minus, .comm_plus {cursor: pointer}
</style>
Ответы (1 шт):
Автор решения: Solt
→ Ссылка
Можно при нажатии к самой кнопке прикрутить класс, чтоб она делалась подсвеченной, а при клике проверять на этот класс и выключать, если уже была включена. Либо хранить массив с id и статусом. Однако, при перезагрузке страницы всё будет забыто. По-хорошему на бэке надо хранить не просто счётчик, а базу данных с информацией кто и что кликал.