WordPress

ajax – Nieprzechwycony błąd referencyjny: custom_ajax nie jest zdefiniowany

  • 23 lipca, 2024
  • 3 min read
ajax – Nieprzechwycony błąd referencyjny: custom_ajax nie jest zdefiniowany


Próbuję utworzyć aplikację, która będzie dodawać produkty do koszyka za pomocą PHP i JavaScript + Ajax. Aby to zrobić, napisałem ten skrypt w functions.php:

// Enqueue Fetch API script
function cart_processing() {
    wp_register_script(
        'custom_fetch_script', 
        get_theme_file_uri('/assets/js/cartProcessing.js'), 
        1.0, 
        true
    );
    
    wp_enqueue_script('custom_fetch_script');
    
    wp_localize_script('custom_fetch_script', 'custom_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'security' => wp_create_nonce('custom_fetch'),
    ));
    
}

add_action('wp_enqueue_scripts', 'cart_processing');

Po stronie front-end dodałem ten skrypt (cartProcessing.js):

document.addEventListener('DOMContentLoaded', function() {
    console.log(custom_ajax.ajax_url);
    console.log(custom_ajax.security);
    
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            let date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }
    
    // add-to-cart button
    const addToCartButton = document.querySelector('.product-actions #cart-icon');
    
    //Listing
    const listing_title_raw = document.querySelector('.product-item .product-details .listing-title').textContent;
    const listing_price_raw = document.querySelector('.product-item .product-details .product-price').textContent;
    
    const listing_price_trimmed = listing_price_raw.split(" ");
    
    const listing = {"title": listing_title_raw, "price": listing_price_trimmed[1]};
    
    if (addToCartButton) {
        addToCartButton.addEventListener('click', function() {
    
            // Convert JSON object to string
            const data = JSON.stringify(listing);

            // Set cookie (expires after 1 day)
            setCookie("listing", data, 1);

            // Send the data to the server using Fetch API
            fetch(custom_ajax.ajax_url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-WP-Nonce": custom_ajax.security
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    action: '../cart-admin.php',
                    listing: listing,
                    security: custom_ajax.security
                })
            })
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('Network response was not ok');
                }
            })
            .then(data => {
                alert("Data saved and sent successfully:", data);
            })
            .catch(error => {
                alert("Failed to send data: " + error.message);
            });
        });
    }
});

Po sprawdzeniu go poprzez kliknięcie przycisku otrzymałem jednak błąd opisany w tytule pytania:
Uncaught ReferenceError: custom_ajax is not defined
Sprawdziłem swój kod, ale nie znalazłem żadnych błędów. Zapytałem również na czacie online, przeczytałem też kilka innych pytań na tym stack exchange, przeszukałem internet i obejrzałem kilka filmów na YouTube, ale wszystkie potwierdziły, że sposób, w jaki to zrobiłem, jest tym, jak należy to zrobić (chyba że coś pominąłem, oczywiście). Czy ktoś mógłby zauważyć jakieś brakujące kroki lub błędy, które mogłem pominąć? Z góry dziękuję!

Warto przeczytać!  Jak dostosować szablon strony dla edytora Gutenberga


Źródło