Hi everyone I try to build web application with using django and js. It is kind of chat application there are rooms and each room have time after time is up. I want to delete room. While I making test, I realize if one user in room,other user in list page, room does not delete when 1 user in room and other list page. Time is stay 1 seconds How can ı solve this problem. Can you help me? Thank You.
room_detail_page
function updateRemainingTime() {
// Sunucuya AJAX isteği gönder
var xhr = new XMLHttpRequest();
xhr.open('GET', '/remaining-time/' + roomName + '/', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var remainingTime = JSON.parse(xhr.responseText);
// Kalan süreyi güncelle
document.getElementById('remaining-time').textContent = remainingTime.minutes + ':' + remainingTime.seconds;
if (remainingTime.minutes <= 0 && remainingTime.seconds <= 0) {
deleteRoom(roomName);
}
}
};
xhr.send();
}
function deleteRoom(roomId) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/delete-room/' + roomId + '/', true);
xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
window.location.href = '/home';
location.reload()
}
};
xhr.send();
}
setInterval(updateRemainingTime, 1000);
room_list_page
function updateRemainingTime(roomId) {
// Sunucuya AJAX isteği gönder
var xhr = new XMLHttpRequest();
xhr.open('GET', '/remaining-time/' + roomId + '/', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var remainingTime = JSON.parse(xhr.responseText);
// Kalan süreyi güncelle
var remainingTimeElement = document.getElementById('remaining-time-' + roomId);
remainingTimeElement.textContent = remainingTime.minutes + ':' + remainingTime.seconds;
if (remainingTime.minutes <= 0 && remainingTime.seconds <= 0 ) {
// If remaining time is 0 or negative, delete the room
deleteRoom(roomId);
}
}
};
xhr.send();
}
// Belirli aralıklarla her oda için zamanı güncelle
function deleteRoom(roomId) {
// Sunucuya AJAX isteği gönder
var xhr = new XMLHttpRequest();
xhr.open('POST', '/delete-room/' + roomId + '/', true);
xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); // Add CSRF token if needed
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
location.reload()
}
};
xhr.send();
}
room_ids.forEach(function(roomId) {
setInterval(function() { updateRemainingTime(roomId); }, 1000); // Her saniyede bir güncelle
});
api.py
def remaining_time_api(request, room_id):
room = Room.objects.get(id=room_id)
remaining_time = room.remaining_time()
seconds = remaining_time.seconds % 60
minutes = (remaining_time.seconds // 60) % 60
return JsonResponse({'minutes': minutes, 'seconds': seconds})
def delete_room(request, room_id):
room = get_object_or_404(Room, id=room_id)
room.delete()
return redirect('/home')