Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

php - Can't use ajax passed value in entire wordpress plugin

I wanted to pass a value from front-end to back-end via ajax, then use that value for a calculation plugin. I managed to pass the value to back-end but I couldn't use it in my calculation function.

I get percent value from a select element in front-end and use it for my calculation. everything works well except I can't pass percent to cal_installment(). I get error 500 in my admin_ajax.php

How can I store percent and pass it?

myplugin.php

require_once MYPLUGIN_DIR . '/inc/calc.php';

add_action('wp_ajax_front_end_action','mypercents_front_end_action');
add_action( 'wp_ajax_nopriv_front_end_action', 'mypercents_front_end_action');

 function mypercents_front_end_action(){

    check_ajax_referer( 'installment_nonce' , '_ajax_nonce' );
    $mypercents = (int) $_POST['value'];
    echo $mypercents . '+';

    // cal_installment('','') is inside calc.php
    $val = cal_installment($price, $mypercents) // get product price from Wordpress with global $product

    $pass_back = $val;
    echo $pass_back[0] . '+' . $pass_back[1];

    wp_die();

 }

calc.php

function cal_installment($price, $percents)
{

  echo '
  <select class="woocommerce-ordering" name="percents" id="percents" onchange="pass_the_value()">
  <option value="10" selected="selected">10%</option>
  ';
  // A sample array
  $products = array(
     20 => "20%",
     30 => "30%",
     40 => "40%",
     50 => "50%",
     60 => "60%",
     70 => "70%"
  );

    foreach ($products as $key => $item) {

      echo "<option value='{$key}'>$item</option>";
  }
  echo '
  </select>
  <div id="succ"></div>
  ';
  echo $percents;
  $pre_pay = $price * $percents;

//some calculation occurs here and then returns calculation result that is an array.

return calc_result;

main.js

jQuery(document).ready(function () {
jQuery('#percents').change(pass_the_value());
});

function pass_the_value() {
    var selected = jQuery('#percents').val();
        jQuery.ajax({
        method: 'POST',
        url: test.ajax_url,
        data: {
            'action': 'front_end_action',
            '_ajax_nonce':test.ajax_nonce,
            'value': selected
        },
    success: function (data) {
        var str = data;
        var result = str.split("+");
        console.log(result);
        jQuery("#succ").html(result);
        
     },
     error: function (jqXHR, status, error) {
     //error handler
      
    });

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...