Question

I want to pass a calculator result to a php file and the result will change the product quantity.

I want to set the starting value to be the result from the calculator page. I have a button on calculator page and after clicking the button the page will go the product page and pass the calculated result to product quantity.

I don't know how to pass it to this php file.

This is my html

     <div>Total: <span id="finaltotalresult">6.864</span>metric tons</div>

    <form method="post"  action="http://carboncreditcapital.com/offset">
    <input type="hidden" name="finalresult">
    <input type="submit" value="Offset Now" id="offset" >
    </form>

javascript:

        $("#offset").on('click',function(){
            var text =$("#finaltotalresult").text();
            var val = Math.round(parseFloat(text));
            $.post('/dev/wp-content/themes/responsive-child/functions.php',{val: val}, function(){

                });
        });

This is the php:

   $val= $_POST['val'];

     add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 );
      function jk_woocommerce_quantity_input_args( $args, $product ) {

         $args['input_value']   = $val; // Starting value
         $args['max_value']     = 80;   // Maximum value
          $args['min_value']    = 1;    // Minimum value
          $args['step']         = 1;    // Quantity steps
          return $args;
    }
Was it helpful?

Solution

I assume you've most likely a scope problem here with the $val variable. As you read it outside of the function

$val = $_POST[ 'val' ];

but you use it inside the function withouth importing it, it's not available there in.

So all you might need to do (the rest of the code doesn't look too wrong but it's hard to tell as I can not reproduce with your example code) is to import that variable there in. An easy way with your code is to use a closure:

$val = $_POST[ 'val' ];

add_filter( 'woocommerce_quantity_input_args', 
    function ( $args, $product ) use ( $val ) 
    {
         $args[ 'input_value' ] = $val; // Starting value
         $args[ 'max_value'   ] = 80;   // Maximum value
         $args[ 'min_value'   ] = 1;    // Minimum value
         $args[ 'step'        ] = 1;    // Quantity steps

         return $args;
    }, 10, 2 );

The other alternative is to make use of the super-global inside your filter function.

OTHER TIPS

You should set the value of the hidden field same as what's in

<input type="hidden" name="finalresult" value="setValueHereUsingBelowJS">

<script>
$('input[name=finalresult]').val(
$('#finaltotalresult').html()
);
</script>

And to access on the server, use $_POST['finalresult'];

You can try using a hidden input:

<input type="hidden" name="result" value="123">

to read it on the receiving php:

$result = $_POST['result'];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top