'PHP - Can't access properties declared in another method when calling methods using AJAX

I apologise if this question is a bit long winded, but it's quite a large chunk of code and I cannot get it to work for the life of me...

I am building a form inside a Wordpress plugin that should gather some data (either through form inputs, API, or a combination of both - such as calling different API endpoints depending on form values). I want to then use these variables (or properties, as they seem to be referred to within classes) in different methods.

Firstly, I have my class and then a method to register my plugin on the Wordpress menu bar:

class EnigmaDMU {
    
    private $enigma_dmu_screen_name;  
    private static $instance;
  
    static function GetInstance()  
    {  
          
        if (!isset(self::$instance))  
        {  
            self::$instance = new self();  
        }  
        return self::$instance;  
    }  
    
    // This loads the WP menu page and plugin page
    public function PluginMenu() {  
     $this->enigma_dmu_screen_name = add_menu_page(  
                                      'Enigma DMU Post',   
                                      'Enigma DMU Post',   
                                      'manage_options',  
                                      __FILE__,   
                                      array($this, 'RenderPage'),   
                                      plugins_url('enigma-daily-update/assets/enigma-cube-white.svg',__DIR__)  
                                      );  
    }

I then have another method called 'RenderPage' which contains my form and the HTML elements for my plugin page inside the WP admin:

public function RenderPage(){
        ?>  
            <div class='wrap'>
                <div class="header-bar">
                    <h1>Daily Market Update</h1>
....... continued here

At the very bottom of my code, I have a method to initiate the plugin which adds the AJAX handlers (my methods) for certain AJAX actions which are called in my AJAX requests:

public function InitPlugin()  {

        add_action('admin_menu', array($this, 'PluginMenu'));
        add_action('admin_enqueue_scripts', array($this, 'dmu_load_scripts'));
        add_action('admin_enqueue_styles', array($this, 'dmu_load_scripts'));

        add_action('wp_ajax_btc_data', array($this, 'getBTCData'));
        add_action('wp_ajax_test_func', array($this, 'testFunc'));
}
} //this is the closing tag for the Class.

Underneath this, I have some class-related definitions, which admittedly I am unsure what they do - this was part of a larger tutorial I followed to set up this plugin:

$EnigmaDMUpost = EnigmaDMU::GetInstance();  
$EnigmaDMUpost->InitPlugin();  

?>

Almost there... I also have my handlers (I have included a test handler to simplify this explanation):

public function getBTCData() {

        require __DIR__."/vendor/autoload.php";
        $client = new GuzzleHttp\Client();

        $btc_curl = $client->get('https://api.alternative.me/v1/ticker/bitcoin/',);
        $btc_curl_body = $btc_curl->getBody();
        $btc_curl_body_json = json_decode($btc_curl_body);

        foreach($btc_curl_body_json as $result){
            $btc_price_ur = $result->price_usd;
            $btc_change_ur = $result->percent_change_24h;
        }

        $btc_price = round($btc_price_ur, 2);
        $btc_change = round($btc_change_ur, 2);
        $this->row3b = $btc_change . '%';

        echo 'inside: ' . $this->row3b;

        die();

    }

I am able to echo this value here (row3b) inside my plugin successfully - this works as expected.

However, when I try and call the property from my testFunc, I get nothing:

public function testFunc() {
        $test_item = $this->row3b;
        echo 'btc dominance = ' . $test_item . '%.';
    }

Finally, the relevant areas of my AJAX script are as follows:

jQuery(document).ready(function($) {
    $('#dmu_submit').click(function() {
        $('#dmu-loader').show();
        $('#dmu_submit').attr('disabled', true);

        btc_data = {
            action: 'btc_data',
            dmu_nonce: dmu_vars.dmu_nonce
        };

        $.post(ajaxurl, btc_data, function(response) {
            $('#dmu-results').html(response);
            $('#dmu-loader').hide();
            $('#dmu_submit').attr('disabled', false);
        });

    $('#dmu_test_func').click(function() {
        $('#dmu-loader').show();
        $('#dmu_submit').attr('disabled', true);

        test_data = {
            action: 'test_func',
            dmu_nonce: dmu_vars.dmu_nonce
        };

        $.post(ajaxurl, test_data, function(response) {
            $('#dmu-results-test').html(response);
            $('#dmu-loader').hide();
            $('#dmu_submit').attr('disabled', false);
        });

        return false;
    });

Any help would be massively appreciated - I know it's a long post, but I feel as if the answer is actually really simple, I just cannot figure it out. It feels as if I'm doing everything right. Thank you!!



Solution 1:[1]

It's not completely clear from your code examples which class your testfunc() is in. But $this in php refers to the instance of the class that it resides within, and the ->row3b refers to a property called row3b (a property is a variable that belongs to the class which is usually defined at the top of the class code). If you're calling $this->row3b within the class itself it will work, but if you need to refer to it from outside the class you will need to instantiate a new instance of the class, and then refer to it with the variable name you assign. E.g.

$myInstance = new theclassname(); $myInstance->row3b;

If the row3b is a static property its slightly different again, you can refer to this outside of the class as theclassname::$row3b

Edit: also ensure that the testfunc resides in the same class that the add_actions are in. The $this in the add_action tells wordpress that it should look for your handler in 'this' class.

Edit2: I think you may also need the die() at the end of your testfunc. Wordpress ajax is funny about this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1