October 21, 2024
Chicago 12, Melborne City, USA
PHP

How can I send data from an API form (with Javascript) to the functions.php file in WordPress e-commerce website?


I am using the Pledge API charity search widget that shows up on a product page so that the user can select a charity which is then sent to the functions.php. For now, I just want the functions.php to display the charity.
My code is as follows:

function add_charity_hidden_field() {
    echo '<input type="hidden" name="charity_data" id="charity_data" value="" />';
}
add_action('woocommerce_after_order_notes', 'add_charity_hidden_field');
add_action('woocommerce_before_add_to_cart_button', 'my_custom_checkout_field');

function my_custom_checkout_field() {
    echo '<div id="Charity"><h3>Charity</h3>';
    echo  '<div class="plg-search" data-partner-key="DATA_PARTNER_KEY">
</div><script>
document.addEventListener("DOMContentLoaded", function () {
    // Create a hidden input to store charity data
    const charityInput = document.createElement("input");
    charityInput.type = "hidden";
    charityInput.name = "charity_data";  // The name will be used to reference in PHP
    charityInput.id = "charity_data";    // Optional: Assign an ID to the input

    // Append the hidden input to the WooCommerce checkout form
    const checkoutForm = document.querySelector("form.checkout");
    if (checkoutForm) {
        checkoutForm.appendChild(charityInput);
    }

    // Function to handle charity data updates
    const updateEvent = data => {
        // Convert the charity data to a string and set it as the value of the hidden input
        charityInput.value = JSON.stringify(data);
        console.log("Charity data updated:", data);  // Debugging: Log the data for confirmation
    }

    // Function to handle the removal of charity data (if applicable)
    const removeEvent = () => {
        charityInput.value = "";  // Clear the hidden input if the event is removed
        console.log("Charity data removed");  // Debugging: Log the removal
    }

    // Function to handle the incoming message from the widget
    const handleMessage = e => {
        // Ensure the message is coming from the correct origin
        if (e.origin !== "https://www.pledge.to") return;

        // Parse the incoming message
        const message = JSON.parse(e.data);

        // Handle the actions based on the message type
        switch (message.action) {
            case "updateEvent":
                return updateEvent(message.data);
            case "removeEvent":
                return removeEvent();
        }
    }

    // Add the message event listener to listen for the charity widgets data
    addEventListener("message", handleMessage);
});
</script>
';
    echo '</div>';
}

// Store custom field
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
    
    if (isset($_POST['charity_data']) && !empty($_POST['charity_data'])) {
        // Sanitize the charity data
        $cart_item_data = sanitize_text_field($_POST['charity_data']);
        echo $cart_item_data;
    } else {
        echo "No charity";
    }
    return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );

It constantly displays "No Charity" even after I select a charity. I know that selecting a charity has worked because it displays the charity in the console.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video