将表单数据发送到unctions.php

时间:2018-04-03 作者:Dimitris HD

我有一个隐藏的输入表单,其中有我的自定义产品价格。我希望每次向购物车添加新项目时,都能将此价格(表单)发送给函数,该价格(表单)是用javascript动态生成的。php使用$\\u POST

代码:

HTML

<input id="hiddenfield" type="hidden" action="functions.php" value="foo" 
     name="hiddenfields" />

        <?php echo do_shortcode(\'[add_to_cart id="212"]\');   ?>
JS FILE

函数totalprice(){

var one=Number(document.getElementById("vol1").value);
var two=Number(document.getElementById("vol2").value);
var three=Number(document.getElementById("vol3").value);
var four=Number(document.getElementById("vol4").value);


var total=one+two+three+four;

var target=document.getElementById("final");

target.innerHTML=total +"€ VDC/ month";

FUNCTIONS.PHP

 add_action(\'woocommerce_before_calculate_totals\',
 \'woocommerce_pj_update_price\'
 , 99 );

function woocommerce_pj_update_price()  {
$custom_price = 100;   
$target_product_id = 212;


    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if($cart_item[\'data\']->get_id() == $target_product_id){

            $cart_item[\'data\']->set_price($custom_price);


    }
}
}

1 个回复
SO网友:dawoodman71

答案是AJAX。每次计算总计时,将表单数据发送给wp ajax处理程序。

Step 1: 将脚本文件排队后,使用wp\\u localize\\u脚本将ajax URL从PHP传递到javascript。

wp_enqueue_script(\'myScript\', \'my/script/path.js\');
wp_localize_script(\'myScript\', \'php_params\', [\'ajaxurl\'=>admin_url(\'admin-ajax.php\')]);
Step 2: 在脚本中进行AJAX调用。

$.ajax({
    type: "POST",
    url: php_params.ajaxurl,
    data: {
        action:\'mytag_function_name\',
        your:\'data\', 
        goes:\'here\'
    },
    success: function(data){
        // do something
    },
    error: function(errorThrown){
        // do something
    }
});
Step 3: 将ajax方法添加到函数中。php文件

add_action( \'wp_ajax_nopriv_mytag_function_name\', \'mytag_function_name\' );
add_action( \'wp_ajax_mytag_function_name\', \'mytag_function_name\' );

function mytag_function_name(){
    // do something with your $_POST data
    $post = filter_input_array(INPUT_POST);
    echo "Here\'s my result to get returned to Javascript";
    die();
}
在WordPress Codex中了解有关AJAX的更多信息:https://codex.wordpress.org/AJAX

希望这有帮助:)

结束

相关推荐