php – Create fields with the value of WooCommerce quantity in single product page using ajax


I want all my trees that are sold on my WordPress site to be registered with a name So I have to get the product quantity value and create a new field for that value so that the user can register any tree with the name in the order on the same page.

But I can’t convert javascript value to php variable on the same page without refreshing the page

How can I do it?

jQuery(document).ready(function($) {
    var $quantityField = $('form.cart').find('input[name="quantity"]');
    $quantityField.on('change input', function() {
        var quantityValue = parseInt($(this).val());

                $.post('<?php echo get_template_directory_uri() ?>/woocommerce/single-product.php', {
            quantity: quantityValue

add_action('woocommerce_before_add_to_cart_button', 'fabric_length_product_field');
function fabric_length_product_field()
     $quantityValue = 1;
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $quantityValue = $_POST["quantity"];

    for ($i = 1; $i <= $quantityValue; $i++) {
      woocommerce_form_field('tree_name' . $i, array(
        'type'     => 'text',
        'label' => 'name of tree'.$i,
        'placeholder' => 'full name',
        'class'    => array('my-field-class form-row-wide'),
        'required' => true, // or false

seyed ehsan ghazi marashi 3 weeks 2023-05-09T08:24:05-05:00 0 Answers 0 views 0

Leave an answer