phpajaxwordpressvariablesadd-filter

Passing php variable in ajax call to add_filter


I am trying to pass a variable that I receive in an ajax call to an add_filter function.

Here is my code

add_action('wp_ajax_mht_set_partial_payment_amount', 'mht_set_partial_payment_amount');
add_action('wp_ajax_nopriv_mht_set_partial_payment_amount', 'mht_set_partial_payment_amount');

function mht_set_partial_payment_amount(){

    $amount = $_POST["partial_payment_amount"];

    add_filter('woo_wallet_partial_payment_amount', function($partial_payment){
        return $amount;
    }, 10, 1);

    echo json_encode($amount);

    die();
}

The $amount is completely okay in the response but it is not working at all in the filter.

I have tried many other ways to pass the $amount variable to the filter(using a class or a global variable) but nothing works.

The ajax call simply takes an input field value. And I need to pass the value to a filter.

I have spent hours on this but no luck :( Any help will be greatly appreciated!


Solution

  • The problem is that AJAX function runs separate from the user page. So I guess that when you add the filter it never executes because it's a AJAX call and not building the page. I would do a $_SESSION variable to temporary store the value and use it in the hook like:

    function mht_set_partial_payment_amount(){
       if (!empty($_POST["partial_payment_amount"]) {
          $_SESSION['my-amount"] = $_POST["partial_payment_amount"];
          echo json_encode($amount);
       }
    
       wp_die(); // Use wp_die for ajax functions.
    }
    

    Always add the filter to execute the call, but the code inside only will be done if the $_SESSION variable exists:

    add_filter('woo_wallet_partial_payment_amount', function($partial_payment){
       if (!empty($_SESSION["my-amount"]) {
            //EXECUTE WHAT YOU WANT
       };
    }