Сохранение кнопки бронирования [закрыто]Javascript

Форум по Javascript
Ответить
Anonymous
 Сохранение кнопки бронирования [закрыто]

Сообщение Anonymous »

У меня есть проблема с сохранением данных о человеке, который нажал, и функции подсчета время бронирования после нажатия кнопки. Я полностью застрял, кто -нибудь из вас знает, как я могу решить это, и где проблема заключается, после нажатия кнопки изменений в зарезервированное время обратного отсчета, но после обновления страницы не сохраняются данные. Таким образом, если какой-либо пользователь входит, он также может нажать эту кнопку, и она должна работать так, чтобы, когда один человек щелкнул, сохранить, кто нажимал, отсчитывает время бронирования 48H назад, блокируя тем самым возможность нажать кнопку для других пользователей, и они видят только то, сколько времени зарезервировано, и после этого времени кнопка должна вернуться к возможности повторного устранения. /> ajax: < /p>
function handle_reservation() {
$user_id = get_current_user_id();
$post_id = intval($_POST['post_id']);

if (!$user_id) {
wp_send_json_error(['message' => 'Musisz być zalogowany, aby rezerwować.']);
}

$current_reservation = get_post_meta($post_id, '_reserved_by', true);
$reserved_until = get_post_meta($post_id, '_reserved_until', true);

if ($current_reservation && time() < $reserved_until) {
wp_send_json_error([
'message' => 'Post już zarezerwowany do ' . date('Y-m-d H:i:s', $reserved_until),
'reserved_by' => get_userdata($current_reservation)->user_login
]);
}

update_post_meta($post_id, '_reserved_by', $user_id);
update_post_meta($post_id, '_reserved_until', time() + 48 * 60 * 60);

wp_send_json_success([
'message' => 'Post zarezerwowany.',
'reserved_by' => get_userdata($user_id)->user_login
]);
}
add_action('wp_ajax_reserve_post', 'handle_reservation');

function check_reservation_status() {
$post_id = intval($_POST['post_id']);
$reservation = get_post_meta($post_id, '_reserved_by', true);
$reserved_until = get_post_meta($post_id, '_reserved_until', true);

if ($reservation && time() < $reserved_until) {
wp_send_json_success([
'reserved' => true,
'reserved_by' => get_userdata($reservation)->user_login,
'time_left' => $reserved_until - time()
]);
} else {
wp_send_json_success(['reserved' => false]);
}
}
add_action('wp_ajax_check_reservation_status', 'check_reservation_status');

function enqueue_reserve_post_script() {
wp_enqueue_script('reserve-post-js', get_template_directory_uri() . '/js/reserve-post.js', ['jquery'], null, true);

wp_localize_script('reserve-post-js', 'wp_vars', [
'ajax_url' => admin_url('admin-ajax.php'),
'user_id' => get_current_user_id()
]);
}
add_action('wp_enqueue_scripts', 'enqueue_reserve_post_script');
< /code>
js: < /p>
document.addEventListener('DOMContentLoaded', function() {
const buttons = document.querySelectorAll('.reserve-button');

buttons.forEach(function(button) {
button.style.backgroundColor = "green";
button.style.color = "white";
button.style.border = "none";
button.style.padding = "10px 20px";
button.style.fontSize = "16px";
button.textContent = "Zarezerwuj";

const postId = button.getAttribute('data-post-id');
const userId = wp_vars.user_id;
const reservationInfo = button.nextElementSibling;
const reservedByElement = reservationInfo.querySelector('.reserved-by');

checkReservation(postId, button, reservationInfo, reservedByElement);

button.addEventListener('click', function() {
reservePost(postId, userId, button, reservationInfo, reservedByElement);
});

button.addEventListener('mouseenter', function() {
if (!button.disabled) {
button.style.backgroundColor = "white";
button.style.color = "orange";
button.style.border = "2px solid orange";
button.textContent = "ZAREZERWUJ";
}
});

button.addEventListener('mouseleave', function() {
if (!button.disabled) {
button.style.backgroundColor = "green";
button.style.color = "white";
button.style.border = "none";
button.textContent = "Zarezerwuj";
}
});
});
});

function checkReservation(postId, button, reservationInfo, reservedByElement) {
jQuery.ajax({
url: wp_vars.ajax_url,
type: 'POST',
data: {
action: 'check_reservation_status',
post_id: postId
},
success: function(response) {
if (response.success && response.data.reserved) {
const { time_left, reserved_by } = response.data;
button.textContent = `Zarezerwowane na ${formatTime(time_left)}`;
button.style.backgroundColor = "orange";
button.style.color = "white";
button.disabled = true;
startCountdown(button, time_left);

reservedByElement.textContent = reserved_by;
reservationInfo.style.display = "block";
}
},
error: function() {
console.error('Błąd podczas sprawdzania rezerwacji.');
}
});
}

function reservePost(postId, userId, button, reservationInfo, reservedByElement) {
jQuery.ajax({
url: wp_vars.ajax_url,
type: 'POST',
data: {
action: 'reserve_post',
post_id: postId,
user_id: userId
},
success: function(response) {
if (response.success) {
const time_left = 48 * 60 * 60;
button.textContent = `Zarezerwowane na ${formatTime(time_left)}`;
button.style.backgroundColor = "orange";
button.style.color = "white";
button.disabled = true;
startCountdown(button, time_left);

reservedByElement.textContent = response.data.reserved_by;
reservationInfo.style.display = "block";
} else {
alert('Nie udało się zarezerwować: ' + response.data.message);
}
},
error: function() {
alert('Błąd podczas rezerwacji.');
}
});
}

function formatTime(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return `${hours}h ${pad(minutes)}m`;
}

function pad(num) {
return num < 10 ? '0' + num : num;
}

function startCountdown(button, remainingTime) {
const countdownInterval = setInterval(() => {
remainingTime -= 1;
if (remainingTime

Подробнее здесь: https://stackoverflow.com/questions/795 ... ion-button
Ответить

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

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

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

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

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