Вывод результатов поиска в блок
Когда я попадаю на страницу results.php в левом блоке выводятся результаты поиска. Рядом с этим блоком расположен календарь, а справа - блоки поиска. Нужно чтобы при клике на дату в календаре - очищался левый блок и блоки поиска, после этого выводить события с датой в левый блок.. Из всего что получилось... при клике на дату - очистка левого блока и поисковых блоков.
'''
<?php
require_once 'connect.php';
if ($_SERVER["REQUEST_METHOD"] === "GET") {
$searchByName = isset($_GET['searchByName']) ? $_GET['searchByName'] : '';
$searchDate = isset($_GET['searchDate']) ? $_GET['searchDate'] : '';
$isAnniversary = isset($_GET['isAnniversary']) ? $_GET['isAnniversary'] : '';
$sql = "SELECT events.*,
(SELECT MAX(files.file_name)
FROM event_files
LEFT JOIN files ON event_files.file_id = files.file_id
WHERE event_files.event_id = events.event_id) AS file_name
FROM events
WHERE 1";
$params = [];
$paramTypes = "";
if (!empty($searchByName)) {
$sql .= " AND (event_name LIKE ? OR event_description LIKE ? OR event_archive_cipher LIKE ?)";
$paramTypes .= "sss";
$searchParam = '%' . $searchByName . '%';
$params[] = $searchParam;
$params[] = $searchParam;
$params[] = $searchParam;
}
if (!empty($searchDate)) {
if (preg_match('/^(\d{4})-(\d{4})$/', $searchDate, $matches)) {
$startDate = $matches[1];
$endDate = $matches[2];
} elseif (preg_match('/^(\d{4})$/', $searchDate, $matches)) {
$startDate = $matches[1];
$endDate = $matches[1];
} else {
$startDate = null;
$endDate = null;
}
if ($startDate !== null && $endDate !== null) {
$sql .= " AND (
(LENGTH(events.event_date) = 4 AND
CAST(events.event_date AS UNSIGNED) BETWEEN ? AND ?) OR
(LENGTH(events.event_date) = 10 AND
STR_TO_DATE(events.event_date, '%d.%m.%Y') BETWEEN ? AND ?)
)";
$paramTypes .= "ssss";
$params[] = $startDate;
$params[] = $endDate;
$params[] = $startDate . '-01-01';
$params[] = $endDate . '-12-31';
}
}
if ($isAnniversary) {
$sql .= " AND ( LENGTH(events.event_date) = 4 OR
DATE_FORMAT(STR_TO_DATE(events.event_date, '%d.%m.%Y'), '%d.%m') = DATE_FORMAT(STR_TO_DATE('21.02.1959', '%d.%m.%Y'), '%d.%m'))";
}
?>
<!DOCTYPE html>
<html lang="en">
<body>
<form method="POST" class="search-form" action="search.php" id="searchForm" style="margin-top:100px">
<div class="container">
<div class="left-side">
<div class="wrapper">
<div style="color: black; font-weight: bold; padding: 20px;" id="searchResults">
<?php
function getYearsSinceEvent($eventDate)
{
// Если дата уже в формате "гггг"
if (strlen($eventDate) === 4) {
$currentYear = date('Y');
$yearsSinceEvent = $currentYear - intval($eventDate);
return $yearsSinceEvent;
}
$eventDateTime = DateTime::createFromFormat('d.m.Y', $eventDate);
if ($eventDateTime !== false) {
$currentDateTime = new DateTime();
$interval = $currentDateTime->diff($eventDateTime);
return $interval->y;
}
return "Ошибка в формате даты";
}
if (!empty($params)) {
$stmt = $conn->prepare($sql);
if ($stmt === false) {
die('Error preparing the query: ' . $conn->error);
}
$stmt->bind_param($paramTypes, ...$params);
if ($stmt->execute()) {
$result = $stmt->get_result();
$totalRecords = $result->num_rows;
echo "<h2 class='text-center' style='margin-top:15px;'>Всего найдено событий: " . $totalRecords . "</h2><br>";
if ($totalRecords > 0) {
while ($row = $result->fetch_assoc()) {
echo '<a class="event-link" href="event-card.php?event_id=' . $row["event_id"] . '" style="text-decoration: none; color: inherit; transition: color 0.3s ease;">';
echo "<h4>•Дата события: " . str_replace('!', '.', $row["event_date"]) . " (" . getYearsSinceEvent($row["event_date"]) . " лет)</h4>";
echo "<h6><u>Название события</u>: " . $row["event_name"] . "</h6>";
$description = $row["event_description"];
$limitedDescription = (strlen($description) > 120) ? substr($description, 0, 120) . '...' : $description;
echo "<h6 style='border-bottom: 2px solid #ccc;'><u>Описание события</u>: " . $limitedDescription . "</h6>";
echo '</a>';
}
} else {
}
} else {
die('Error executing the query: ' . $stmt->error);
}
$stmt->close();
}
$conn->close();
}
?>
<div class="event">
<h2></h2>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
<script>
let currentDate = new Date();
function updateCalendarView() {
const monthAndYear = currentDate.toString('MMMM yyyy');
document.getElementById('monthAndYear').textContent = monthAndYear;
}
function previous() {
currentDate = currentDate.add(-1).month();
updateCalendarView();
}
function next() {
currentDate = currentDate.add(1).month();
updateCalendarView();
}
document.addEventListener('DOMContentLoaded', function () {
updateCalendarView();
document.getElementById('previous').addEventListener('click', function (event) {
event.stopPropagation();
event.preventDefault();
previous();
});
document.getElementById('next').addEventListener('click', function (event) {
event.stopPropagation();
event.preventDefault();
next();
});
});
</script>
<div class="wrapper">
<div class="container-calendar">
<div id="">
<div class="header-container-calendar">
<div class="button-container-calendar">
<button type="button" id="previous" onclick="previous()">
‹
</button>
<h3 id="monthAndYear"></h3>
<button type="button" id="next" onclick="next()">
›
</button>
</div>
</div>
<table class="table-calendar" id="calendar" data-lang="ru">
<thead id="thead-month"></thead>
<!-- Table body for displaying the calendar -->
<tbody id="calendar-body"></tbody>
</table>
<div class="footer-container-calendar text-center">
<label for="month"></label>
<select id="month" onchange="jump()">
<option value=0>Январь</option>
<option value=1>Февраль</option>
<option value=2>Март</option>
<option value=3>Апрель</option>
<option value=4>Май</option>
<option value=5>Июнь</option>
<option value=6>Июль</option>
<option value=7>Август</option>
<option value=8>Сентябрь</option>
<option value=9>Октябрь</option>
<option value=10>Ноябрь</option>
<option value=11>Декабрь</option>
</select>
<!-- Dropdown to select a specific year -->
<select id="year" onchange="jump()"></select>
<span>год</span>
</div>
</div>
</div>
</div>
<script src="./resscript.js"></script>
</div>
<div class="right-side">
<div class="wrapper">
<div class="search-container" style="background-color:white; ">
<div class="bordered-container">
<label for="searchByName">Поиск по ключевым словам</label>
<div class="tooltip-container">
<input type="text" name="searchByName" id="searchByName"
value="<?php echo isset($searchByName) ? $searchByName : ''; ?>"
onblur="validateInput()" class="text-center">
<span class="tooltip-text">Введите ключевые слова для поиска. Можно использовать
одно или несколько слов.</span>
</div>
</div>
</div>
<div class="search-container" style="background-color:white;">
<div class="bordered-container">
<label for="searchDate">Поиск по дате</label>
<div class="tooltip-container">
<input type="text" pattern="\d{4}-\d{4}|\d{4}" id="searchDate"
value="<?php echo isset($searchDate) ? $searchDate : ''; ?>" name="searchDate"
class="text-center">
<span class="tooltip-text">Поддерживается поиск по периоду и по году <br> (например,
1916-1920 или 1916).</span>
</div>
<div class="error-message" id="searchDateError"></div>
</div>
</div>
<div class="search-container" style="background-color:white;text-align: center;" id="checkboxDiv">
<div class="bordered-container">
<label for="isAnniversary" class="checkbox-label">Юбилейная дата?</label>
<div class="tooltip-container">
<input type="checkbox" id="isAnniversary" class="demoToggleCheckbox" name="isAnniversary"
<?php echo $isAnniversary ? 'checked' : ''; ?>>
<label for="isAnniversary" class="checkbox-toggle"></label>
<span class="tooltip-text">Отметьте, если ищете юбилейные даты.</span>
</div>
</div>
</div>
<div id="reminder-list"></div>
<div class="button-row">
<div>
<div class="tooltip-container">
<button type="submit" class="search" style="font-size: large;">
<img src="play-button_1710004.png" width="64" height="64">
</button>
<span class="tooltip-text">Поиск</span>
</div>
</div>
<div class="tooltip-container">
<div>
<a href="#" id="clear-button" class="clear" style="font-size: large;margin-left: 10px;">
<img src="cross-red.webp" width="64" height="64">
</a>
<span class="tooltip-text">Очистить</span>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script>
$(document).ready(function () {
$("#searchForm").submit(function (event) {
event.preventDefault();
var formData = $(this).serialize();
sendAjaxRequest(formData);
});
document.querySelector('.search-form').addEventListener('submit', function (e) {
e.preventDefault();
var searchByName = document.getElementById('searchByName').value;
var searchDate = document.getElementById('searchDate').value;
var isAnniversary = document.getElementById('isAnniversary').checked;
searchResults(searchByName, searchDate, isAnniversary);
});
document.getElementById('clear-button').addEventListener('click', clearFormAndResults);
function searchResults(searchByName, searchDate, isAnniversary) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('searchResults').innerHTML = this.responseText;
}
};
xhttp.open("POST", "search.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("searchByName=" + searchByName + "&searchDate=" + searchDate + "&isAnniversary=" +
isAnniversary);
}
function clearFormAndResults(event) {
event.preventDefault();
clearForm();
clearSearchResults();
clearURLParameters();
}
function clearForm() {
$("#searchForm")[0].reset();
$("#searchByName").val('');
$("#searchDate").val('');
document.getElementById('isAnniversary').checked = false;
}
$("#clearButton").click(function (e) {
e.preventDefault();
clearFormAndResults();
clearCheckbox();
});
function clearSearchResults() {
$("#searchResults").empty();
}
function clearURLParameters() {
var newUrl = window.location.href.split("?")[0];
window.history.replaceState({}, document.title, newUrl);
}
});
</script>
</div>
</body>
</html>
'''
resscript.js
let monthAndYear = document.getElementById("monthAndYear");
let tbl = document.getElementById("calendar-body");
document.addEventListener('DOMContentLoaded', function () {
let today = new Date();
let currentMonth = today.getMonth();
let currentYear = today.getFullYear();
let selectYear = document.getElementById("year");
let selectMonth = document.getElementById("month");
let monthAndYear = document.getElementById("monthAndYear");
let reminderList = document.getElementById("reminder-list");
let events = [];
let months = [
"Январь", "Февраль", "Март", "Апрель", "Май", "Июнь",
"Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"
];
let days = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"];
let dataHead = "<tr>";
for (let day of days) {
dataHead += `<th data-days='${day}'>${day}</th>`;
}
dataHead += "</tr>";
document.getElementById("thead-month").innerHTML = dataHead;
function generateYearRange(start, end) {
let years = "";
for (let year = start; year <= end; year++) {
years += `<option value='${year}'>${year}</option>`;
}
return years;
}
function daysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
function clearForm() {
document.getElementById('searchByName').value = '';
document.getElementById('searchDate').value = '';
document.getElementById('isAnniversary').checked = false;
}
function clearSearchResults() {
document.getElementById('searchResults').innerHTML = '';
}
function getEventsOnDate(date, month, year) {
return events.filter(event => {
let eventDate = convertDateStringToDateObject(event.date);
return (
eventDate.getDate() === date &&
eventDate.getMonth() === month &&
eventDate.getFullYear() === year
);
});
}
function hasEventOnDate(date, month, year) {
return getEventsOnDate(date, month, year).length > 0;
}
function createEventTooltip(date, month, year) {
let tooltip = document.createElement("div");
tooltip.className = "event-tooltip";
let eventsOnDate = getEventsOnDate(date, month, year);
for (let event of eventsOnDate) {
let eventDate = convertDateStringToDateObject(event.date);
let eventText = `<strong>${event.title}</strong> - ${event.description} on ${eventDate.toLocaleDateString()}`;
let eventElement = document.createElement("p");
eventElement.innerHTML = eventText;
tooltip.appendChild(eventElement);
}
return tooltip;
}
function convertDateStringToDateObject(dateString) {
const parts = dateString.split(".");
const day = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const year = parseInt(parts[2], 10);
return new Date(year, month, day);
}
function clearFormAndResults(event) {
event.preventDefault();
clearForm();
clearSearchResults();
clearURLParameters();
document.getElementById('searchResults').innerHTML = '';
}
function showCalendar(month = today.getMonth(), year = today.getFullYear(), clearSearch = false) {
if (clearSearch) {
clearForm();
clearSearchResults();
let eventDiv = document.querySelector('.event');
if (!eventDiv) {
eventDiv = document.createElement('div');
eventDiv.classList.add('event');
document.body.appendChild(eventDiv); // или добавьте его в нужное место в вашем HTML-коде
}
eventDiv.innerHTML = ''; // очищаем блок с событиями
}
let firstDay = new Date(year, month, 1).getDay();
let daysToSkip = (firstDay + 6) % 7; // This will ensure that the calendar starts from Monday
let tbl = document.getElementById("calendar-body");
tbl.innerHTML = "";
monthAndYear.innerHTML = `${months[month]} ${year}`;
selectYear.value = year;
selectMonth.value = month;
let date = 1;
for (let i = 0; i < 6; i++) {
let row = document.createElement("tr");
for (let j = 0; j < 7; j++) {
if (i === 0 && j < daysToSkip) {
let cell = document.createElement("td");
let cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
} else if (date > daysInMonth(month, year)) {
break;
} else {
let cell = document.createElement("td");
cell.setAttribute("data-date", date);
cell.setAttribute("data-month", month + 1);
cell.setAttribute("data-year", year);
cell.setAttribute("data-month_name", months[month]);
cell.addEventListener('click', function () {
let clickedDate = this.getAttribute("data-date");
let clickedMonth = parseInt(this.getAttribute("data-month"));
let clickedYear = this.getAttribute("data-year");
clearForm();
clearSearchResults();
let eventDiv = document.querySelector('.event');
if (eventDiv) {
eventDiv.innerHTML = '';
}
let previouslySelected = document.querySelector('.selected');
if (previouslySelected) {
previouslySelected.classList.remove('selected');
}
this.classList.add('selected');
let url = `get_events_by_date.php?date=${clickedDate}&month=${clickedMonth}&year=${clickedYear}`;
let monthNames = ['Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря'];
fetch(url)
.then(response => response.json())
.then(data => {
let eventDiv = document.querySelector('.event');
if (eventDiv) {
eventDiv.innerHTML = "";
if (data.length > 0) {
let monthName = monthNames[clickedMonth - 1];
eventDiv.innerHTML += `<h2>События ${clickedDate} ${monthName}</h2>`;
data.forEach(event => {
let eventDate = event.event_date.split(".");
let eventMonthName = monthNames[eventDate - 1];
let eventText = `<div class="event-details tooltip-container" style="text-align: left;">
<a style="font-size: 20px" class="event-link" href='http://192.168.0.100/event-card.php?event_id=${event.event_id}'>
•
${eventDate} ${eventMonthName} ${eventDate} - ${event.event_name}: ${event.event_description}
</a>
<span class="tooltip-text">Нажмите, чтобы ознакомиться подробнее</span>
</div>`;
eventDiv.innerHTML += eventText;
});
} else {
let clickedMonthIndex = clickedMonth - 1;
let formattedDate = `${clickedDate} ${monthNames[clickedMonthIndex]} ${clickedYear}`;
eventDiv.innerHTML += `<h4 style="text-align: center; color: red; margin-top:45%">На ${formattedDate.slice(0, -5)} события отсутствуют </h4>`;
}
}
})
.catch(error => console.error('Error fetching events:', error));
});
cell.className = "date-picker";
cell.innerHTML = "<span>" + date + "</span>";
if (
date === today.getDate() &&
year === today.getFullYear() &&
month === today.getMonth()
) {
cell.className = "date-picker selected";
}
if (hasEventOnDate(date, month, year)) {
cell.classList.add("event-marker");
cell.appendChild(createEventTooltip(date, month, year));
}
row.appendChild(cell);
date++;
}
}
tbl.appendChild(row);
}
displayReminders();
}
let years = generateYearRange(1970, 2050);
document.getElementById("year").innerHTML = years;
document.getElementById("next").addEventListener('click', next);
document.getElementById("previous").addEventListener('click', previous);
selectYear.addEventListener('change', jump);
selectMonth.addEventListener('change', jump);
showCalendar(currentMonth, currentYear);
function next() {
currentYear = currentMonth === 11 ? currentYear + 1 : currentYear;
currentMonth = (currentMonth + 1) % 12;
showCalendar(currentMonth, currentYear);
}
});
get_events_by_date.php
<?php
require_once 'connect.php';
$date = $_GET['date'];
$month = $_GET['month'];
$year = $_GET['year'];
$formattedDate = sprintf('%02d.%02d.%04d', $date, $month, $year);
$sql = "SELECT event_id, event_name, event_description, event_date FROM events WHERE DAY(STR_TO_DATE(event_date, '%d.%m.%Y')) = '$date' AND MONTH(STR_TO_DATE(event_date, '%d.%m.%Y')) = '$month'";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
$events = array();
while ($row = $result->fetch_assoc()) {
$events[] = $row;
}
header('Content-Type: application/json');
echo json_encode($events);
?>