0

I want to access to variable "$sha256" from one function in other one that use both of them an add_action for Ajax call. I read that I must use a class function and add add_action with construct. I followed advice from [codex][1], but it seems I always an error ! Currently my Jquery Ajax call doesn't send response from functions.php.

Could you please tell me why ? Here is an example from my code:

class sendObjectClass{ 
    $sha256 = "";
    public function __construct() {
        add_action( 'wp_ajax_vault', array( $this ,'vault' )); 
        add_action( 'wp_ajax_nopriv_ vault', array( $this ,'vault' ));

        add_action( 'wp_ajax_ retrievedK', array( $this ,'retrievedK' )); 
        add_action( 'wp_ajax_nopriv_ retrievedK', array( $this ,'retrievedK'));
    }
    public function vault(){
       $sha256 = .....;
       echo json_encode(some elements);
    }
    public function retrievedK(){
       echo json_encode($sha256);
    }
}

Must I add : new sendObjectClass(); ?

Thanks for your help.
[1]: https://developer.wordpress.org/reference/functions/add_action/#div-comment-355

Edit: With the advice I received I tried this but it doesn't work. I work inside function.php.

class ajaxgenk_handler
{
    
    private string $hash;
    private $C1 = array();

    public function __construct(string $hash, $C1)
    {
            $this->hash = $hash;
            $this->C1 = $C1;
    }

    public function run()
    {

        add_action( 'wp_ajax_vault', array( $this, 'vault' )); 
        add_action( 'wp_ajax_nopriv_vault',  array( $this, 'vault' ));

        add_action( 'wp_ajax_retrievedK', array( $this, 'retrievedK' ) ); 
        add_action( 'wp_ajax_nopriv_retrievedK', array( $this , 'retrievedK' ) );
    }

    public function vault()
    {
      
       //php code to generate vars for decrypt1 array
       $decrypt1 = array($kchrfst, $kintfst, $kchrlst, $kintlst);
       $logiq = 1;
                
        $datasecure['keygen'] = $this->C1;
        $datasecure['decryptor'] = $decrypt1;
        $datasecure['enigma'] = $logiq;
        echo json_encode($datasecure);
        
        wp_die();
    }
    
    public function retrievedK()
    {
        echo json_encode(['retrik' => $this->hash]);
        wp_die();
    }
}

require_once( get_template_directory() .'/cryptograph.php'); 
    use class\Cryptograph;

add_action( 'plugins_loaded', 'genk_handler' );
function genk_handler() {
    
    //php code to generate vars for $C1 array

    $C1 = array($fstcchr, $fstint, $lstchr, $lstint,$fstchrpos,$lstchrpos);
    $hash = 'thekeygenerated';
    
    $handler = new ajaxgenk_handler($hash,$C1);

    $handler->run();
}

1 Answer 1

0

Unless the value of the $sha256 property is hard-coded in the class, you need to store it somewhere (database, file,...) so that you can use it in a different Ajax request.

Once the request to wp_ajax_vault is processed and a response is sent back to the requester all the data in the class properties is lost, if it's not saved to some persistent place. When your class handles the wp_ajax_retrievedK request, it is happily unaware that it has ever responded to a wp_ajax_vault request.

Within the same request you can naturally update the class properties with new values and then read them in other class methods.

Couple other things to notice

  • make sure there are no unnecessary spaces in the hook names
  • terminate the ajax handler function/method after the processing is done to return a proper response - use e.g. exit(), die(), wp_die(), wp_send_json(), wp_send_json_success() or wp_send_json_error().

Here are couple simplified examples on how you could address these issues.

Example 1, using a class

class MyAjaxHandler
{
    private string $sha256;

    public function __construct(string $hash)
    {
        $this->sha256 = $hash;
    }

    public function run()
    {
        add_action( 'wp_ajax_vault', array( $this, 'vault' ) ); 
        add_action( 'wp_ajax_nopriv_vault', array( $this, 'vault' ) );

        add_action( 'wp_ajax_retrievedK', array( $this, 'retrievedK' ) ); 
        add_action( 'wp_ajax_nopriv_retrievedK', array( $this , 'retrievedK' ) );
    }

    public function vault()
    {
        // handle authentication, authorization, validation, etc.

        // processing...
        echo json_encode(['data' => $this->sha256]);

        // termination
        wp_die();
    }
    
    public function retrievedK()
    {
        // handle authentication, authorization, validation, etc.

        // processing...
        echo json_encode(['data' => $this->sha256]);

        // termination
        wp_die();
    }
}

add_action( 'plugins_loaded', 'my_prefix_init_handler' );
function my_prefix_init_handler() {
    $hash = 'foo'; // hard-coded, read from a file, retrieve from a databse...
    
    $handler = new MyAjaxHandler($hash);

    $handler->run();
}

UPDATE 2.6.2023

function genk_handler() {
    $hash = 'thekeygenerated';

    $cryptograph = new Cryptograph(
        // some parameters the class needs...
    );
    
    $handler = new ajaxgenk_handler($hash, new Cryptograph);

    $handler->run();
}

class ajaxgenk_handler
{
    private string $hash;
    private Cryptograph $cryptograph;

    public function __construct(string $hash, Cryptograph $cryptograph)
    {
        $this->hash = $hash;
        $this->cryptograph = $cryptograph;
    }

    public function vault()
    {
        $secureData = $this->cryptograph->generate(); // pseudo method, edit as needed
        
        echo json_encode($secureData);

        wp_die();
    }
}

Example 2, using namespace

namespace My\Plugin;

add_action( 'wp_ajax_vault', __NAMESPACE__ . '\\vault' ); 
add_action( 'wp_ajax_nopriv_vault', __NAMESPACE__ . '\\vault' );

add_action( 'wp_ajax_retrievedK', __NAMESPACE__ . '\\retrievedK' )); 
add_action( 'wp_ajax_nopriv_retrievedK', __NAMESPACE__ . '\\retrievedK'));

function vault() {
    // handle authentication, authorization, validation, etc.

    // processing...
    $sha256 = get_my_sha256();

    // response
    wp_send_json_success(['data' => 'acme']);
}

function retrievedK() {
    // handle authentication, authorization, validation, etc.

    // processing...
    $sha256 = get_my_sha256();

    // response
    wp_send_json_success(['data' => 'acme']);
}

function get_my_sha256() {
    return get_transient(my_transient_name());
}

function save_my_sha256($value) {
    set_transient(my_transient_name(), $value, HOUR_IN_SECONDS);
}

function my_transient_name() {
    return 'foo';
}
7
  • Thanks. I store comparison key in generated php file and check it at submit action. I Appreciate this solution for dedicated plugin, but currently I use functions.php from Theme. I will analyze our advice and check my code .
    – imagIne
    May 30 at 12:22
  • the string to be hash, with other Cryptographic hash functions, is generated in vault functions, how can I pass the hash variable between vault and retrievedK functions ? Does my code that generate the string to be hashed must be located in __construct function ?
    – imagIne
    May 30 at 13:18
  • I edit my question, could you please tell me what could create error 400 ? I'm not sure how to instantiate array and if $hash and $C1 vars are well pass through functions inside class.
    – imagIne
    Jun 1 at 12:00
  • @imagIne As for the 400 error, check your js script that it is calling the correct ajax action and url. In your original code you had spaces in the wp_ajax_nopriv_ action names, which I removed in my answer. Jun 2 at 10:35
  • @imagIne If Cryptograph class handles encrypting and decrypting, then you could instantiate new object from the class and pass that as a parameter to ajaxgenk_handler object and store it as a class property instead of passing array to the handler class - this is called dependency injection. Then use the Cryptograph object methods to encrypt and decrypt data as needed within the handler methods. Jun 2 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.