admin管理员组

文章数量:1122832

I am trying to create an application that will add products to a cart using PHP and JavaScript + Ajax. In order to do so, I have written this script in 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');

On the front-end side I added this script (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);
            });
        });
    }
});

After testing it by clicking on the button however, I got the error referenced in the title of this question: Uncaught ReferenceError: custom_ajax is not defined I checked my code but I could not find any errors. I also asked on an online chatroom, I also read some other questions on this stack exchange, searched online and I checked out some YouTube videos but they all confirmed that the way I did it is how it should be done (unless I missed something of course). Could anyone spot any missing steps or mistakes here that I may have left out? Thanks in advance!

本文标签: ajaxUncaught ReferenceError customajax is not defined