• neforzon

    (@neforzon)


    I noticed that my html code that creates the button does not read the post id, in the Logs it shows “[13-Mar-2025 14:16:39 UTC] Checking reservation status for Post ID: 0” which means that it does not read this id.

    I tried to use <?php echo get_the_ID(); ?> instead of {post.id}

    However, using this breaks my page and all elements do not keep their layout, also buttons disappears.

    Do you have an idea how to fix this?

    I made it that way, because i am using generateblocks plugin to make query loop, and my query loop is in Custom Type Post.

    I forgot to mention that my query loop only creates elements on the page but I can’t go further into the posts, I mean that it creates elements on the page where the reservation buttons are.

    HTML:

    <button class="reserve-button"
    data-post-id="{post.id}"
    data-user-id="{current_user.id}"
    data-reserved="{post_meta._reserved_by ? 'true' : 'false'}">
    Zarezerwuj
    </button>
    <div class="reservation-info" style="display: none;">
    Zarezerwowane przez: <span class="reserved-by"></span>
    </div>

    AJAX:

    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');

    JS:

    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 <= 0) {
                clearInterval(countdownInterval);
                button.textContent = "Zarezerwuj ponownie";
                button.style.backgroundColor = "green";
                button.style.color = "white";
                button.disabled = false;
            } else {
                button.textContent = Zarezerwowane na ${formatTime(remainingTime)};
            }
        }, 1000);
    }

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Plugin Support ying

    (@yingscarlett)

    Hi there,

    We won’t be able to debug for codes from 3rd party, and your link doesn’t work.

    I can take a look for you if you can re-attach the correct page link 🙂

Viewing 1 replies (of 1 total)

The topic ‘action button reservation’ is closed to new replies.