0

I have a class that has ajax callbacks inside it, as well as actions set in the __construct() of that class. I am also passing the property to the class when instantiating it. It looks kinda like this

<?php

class My_Class{

    private $passed_string;

    public function __construct( $passed_string ) {
        $this->$passed_string = $passed_string;

        add_action( 'wp_ajax_my_callback', array( $this, 'my_callback' ) );
    }

    public function my_callback() {

        error_log( print_r( $this->$passed_string, true ) );
        wp_die();
    }

}

$init = new My_Class( 'Passed string!' );

Now this should show in my error logs when I call this function with ajax. But it's empty.

The callback works (tested).

The thing is that when doing this in a similar class that has a method inside, that is not hooked to wp_ajax hook it works, and I see the passed string just fine.

How come?

-1

Have you used AJAX before? Do you know what the acronym stands for? Hint: The J stands for javascript. Indeed, AJAX is usually invoked using javascript/jQuery. I believe that's why you're not receiving a response: you aren't invoking an AJAX protocol or going through Wordpress's admin-ajax.php.

And, why would you put a callback function in a constructor in the first place?

  • No, never ever used ajax before.... :roll: If you have a better suggestion for where to put the hook for ajax callback then by all means do tell... – dingo_d Apr 1 '17 at 7:41
  • May I suggest you start by reading the Wordpress Codex (codex.wordpress.org/AJAX) and then google "using ajax in wordpress." If the use cases presented don't match what you are trying to do, then you don't need AJAX! – scott Apr 3 '17 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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