Количество уведомлений не обновляется правильно для консультантов в системе уведомлений PHP + JSPhp

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Количество уведомлений не обновляется правильно для консультантов в системе уведомлений PHP + JS

Сообщение Anonymous »

Я строю систему уведомлений PHP + JavaScript для моего веб -приложения MedConnect. Пользователи и консультанты имеют отдельные инструментальные панели (user_consult.php, consultant_consult.php), каждый из которых со своим собственным выпадающим списком уведомлений и значком подсчета уведомлений. 0. /> База данных: < /p>
Структура таблицы уведомлений: < /p>

id < /li>
user_id < /li>
consultant_id < /li>
consultation_id < /li>


/> Сообщение < /li>
receent_role (enum 'user', 'consultant') < /li>
is_read (tinyint (1), по умолчанию 0) < /li>
create_at < /li>
< /ul>
prose_consult.php: < /p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p>function fetchNotifications() {
fetch('notifications.php?action=fetch')
.then(response => response.json())
.then(data => {
const notificationList = document.getElementById("notification-list");
notificationList.innerHTML = '';

if (data.length === 0) {
notificationList.innerHTML = '
No notifications.
';
return;
}

data.forEach(notification => {
const div = document.createElement('div');
div.classList.add('notification-item');
div.innerHTML = `
${notification.message}
${new Date(notification.created_at).toLocaleString()}
`;
notificationList.appendChild(div);
});
})
.catch(err => console.error(err));
}

function clearAllNotifications() {
fetch('notifications.php?action=clear')
.then(() => {
fetchNotifications(); // refresh the notification list
fetchNotificationCount(); // refresh the count immediately
})
.catch(err => console.error(err));
}

function toggleNotifications() {
const dropdown = document.getElementById('notificationsDropdown');
dropdown.style.display = (dropdown.style.display === 'block') ? 'none' : 'block';

if (dropdown.style.display === 'block') {
fetchNotifications();
fetch('notifications.php?action=markAllRead')
.then(() => fetchNotificationCount()); // refresh count after marking as read
}
}

function fetchNotificationCount() {
fetch('notifications.php?action=count')
.then(response => response.json())
.then(data => {
const count = data.count || 0;
document.getElementById("notification-count").innerText = count;
})
.catch(error => console.error("Error fetching notification count:", error));
}

// Initial load
document.addEventListener("DOMContentLoaded", () => {
fetchNotifications();
fetchNotificationCount();
});
< /code>
consultant_consult.php js: < /p>
function clearAllNotifications() {
fetch('notifications.php?action=clear')
.then(() => {
fetchNotifications(); // refresh the notification list
fetchNotificationCount(); // refresh the count immediately
})
.catch(err => console.error(err));
}

function toggleNotifications() {
const dropdown = document.getElementById('notificationsDropdown');
dropdown.style.display = (dropdown.style.display === 'block') ? 'none' : 'block';

if (dropdown.style.display === 'block') {
fetchNotifications();
fetch('notifications.php?action=markAllRead')
.then(() => fetchNotificationCount()); // refresh count after marking as read
}
}

function fetchNotificationCount() {
fetch('notifications.php?action=count')
.then(response => response.json())
.then(data => {
const count = data.count || 0;
document.getElementById("notification-count").innerText = count;
})
.catch(error => console.error("Error fetching notification count:", error));
}

// Initial load
document.addEventListener("DOMContentLoaded", () => {
fetchNotifications();
fetchNotificationCount();
});

function toggleNotifications() {
const dropdown = document.getElementById('notificationsDropdown');

// Toggle Dropdown Visibility
const isVisible = dropdown.style.display === 'block';
dropdown.style.display = isVisible ? 'none' : 'block';

// If opening, fetch notifications & reset unread count
if (!isVisible) {
fetch('notifications.php?action=markAllRead')
.then(() => fetchNotificationCount()); // refresh count

fetch('consultant_consult.php?fetchConsultations=true')
.then(response => response.json())
.then(data => {
const notificationList = document.getElementById("notification-list");
notificationList.innerHTML = "";

if (data.length === 0) {
notificationList.innerHTML = '
No notifications.
';
return;
}

if (data.error) {
notificationList.innerHTML = `
${data.error}
`;
return;
}

// Display consultations in the dropdown
data.forEach(item => {
let html = "";
if (item.is_notification) {
// Render user activity notifications
html = `

${item.message}
${new Date(item.created_at).toLocaleString()}

`;
} else {
// Render pending consultation requests (existing)
html = `

From: ${item.user_name}
Symptoms: ${item.symptoms}
Date: ${item.date} | Time: ${item.time}
${item.medical_docs ? `
View Medical Documents
` : ""}

Accept
Reject


`;
}
notificationList.innerHTML += html;
});

// Reset unread count to zero (since the user has now read them)
unreadNotificationCount = 0;
document.getElementById("notification-count").innerText = unreadNotificationCount;
})
.catch(error => console.error("Error fetching consultations:", error));
}
}

// Allow clicking on overlay to close the dropdown
document.getElementById('overlay').addEventListener('click', function() {
document.getElementById('notificationsDropdown').style.display = 'none';
this.style.display = 'none';
});
< /code>
notifications.php (count action): < /p>
// COUNT unread notifications
if ($action === 'count') {
if ($role === 'user') {
$stmt = $connection->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND recipient_role = 'user' AND is_read = 0");
} elseif ($role === 'consultant') {
$stmt = $connection->prepare("SELECT COUNT(*) FROM notifications WHERE consultant_id = ? AND recipient_role = 'consultant' AND is_read = 0");
} else {
echo json_encode(['count' => 0]);
exit;
}

if (!$stmt) {
echo json_encode(['error' => 'Prepare failed: ' . $connection->error]);
exit;
}

$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
echo json_encode(['count' => $count]);
$stmt->close();
exit;
}
< /code>
То, что я пробовал:
✅ Проверенные уведомления вставлены с receurient_role = 'consultant' и is_read = 0.
✅ Проверить, что ручные запросы SQL возвращают правильный счет. Я удалил противоречивые интервалы. < /P>
Что мне нужно:
✅ Помощь в определении того, почему значок подсчета уведомлений консультанта не обновляется надежно.>

Подробнее здесь: https://stackoverflow.com/questions/796 ... notificati
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Php»