I'm trying to write an OOP plugin, pass my shortcode arguments to the class, store them as class variables and then use them in an AJAX call.

Here is an example:

class WPAJAXClassTest {
    private $message;
    public function __construct() {
        add_action('wp_enqueue_scripts', array($this,'enqueue_scripts'));
        add_action( 'wp_ajax_testAJAX', array($this,'testAJAX'));
        add_action( 'wp_ajax_nopriv_testAJAX', array($this,'testAJAX'));
    }
    function wpAJAXClassTest($args) {
        $msg=shortcode_atts(array(
            'message' => 'Hello World!'
            ), $args
        );
        $this->setMessage($msg['message']);
        $html="<button id='testbutton'>test</button><p id='testreturn'>".$msg['message']." - ".$this->message."</p>";
        return $html;
    }
    public function setMessage($m) {
        $this->message=$m;
    }
    function enqueue_scripts() {
        $plugin_url = plugins_url()."/wpajaxclasstest";
        wp_enqueue_script('wpajaxclasstest_script', $plugin_url.'/js/plugin.js', array("jquery"));
        wp_localize_script( 'wpajaxclasstest_script', 'myASPlugin', array('plugin_dir' => $plugin_url));
        wp_localize_script( 'wpajaxclasstest_script', 'myAJAX', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
    }
    function testAJAX() {
        header("Content-Type: application/json");
        $returnArray=array();
        $returnArray['message']=$this->message;
        echo json_encode($returnArray);
        exit();
    }
}

I have a simple javascript which calls the AJAX function

$.ajax({
    url: myAJAX.ajaxurl,
    data: json,
    method: "POST",
    error: function(data) {
        alert("Error! "+JSON.stringify(data));
    },
    success: function(data) {
        alert(JSON.stringify(data));
    }
});

My issue is that when I use my shortcode [wpAJAXClassTest] or [wpAJAXClassTest message='Goodbye Cruel World!'] I always get a json return of {"message": "null"} and not the class variable $message I was expecting.

I don't want to use a static getinstance as I want to be able to have multiple instances of the same plugin on the same page.

How do I get my AJAX function to access class variable?

To Clarify:

I want to have 2 buttons on a page driven by shortcode tags

[testAJAX message="hello"]

and

 [testAJAX message="world"]

when I click one button the AJAX function should return {"message": "hello"} and the other should return {"message": "world"}

  • I guess you have add_shortcode somewhere? The problem is likely that your AJAX request is a completely different request from the request to the post/page where your shortcode got interpreted in the content, so what you've evaluated in the shortcode hasn't happened in the AJAX request. – janh Feb 5 at 19:24
  • You also have none of the instantiation code for your class, what does your class pass through as a variable? Where is your add_action('wp_ajax_blah_blah','function here'); This is important as well. This feels copied from a tutorial? – Cam Feb 5 at 21:05
  • Thanks Janh. Yes I have an add shortcode $test=new WPAJAXClassTest(); add_shortcode( 'wpajaxclasstest', array( $test, 'wpAJAXClassTest' ) ); I didn't want to flood the place with code and @cam my "installation code" is right there in the _construct() function. The AJAX request works and will pass back anything I tell it to EXCEPT its class variables! ?????? – stuporllama Feb 6 at 9:18
  • janh has explaind that in the first comment : the AJAX call is a new HTTP request then it's a new instance and you have to define the message again – mmm Feb 6 at 12:42

to pass a variable from JavaScript to the AJAX call, you have to put the message in the data :

data : {"message" : "my message"}

and you retrieve it in the PHP code :

function testAJAX() {

    $returnArray = array();
    $returnArray['message'] = $_POST["message"];

    wp_send_json($returnArray);
}

you can read about the use of wp_send_json here :
https://codex.wordpress.org/Function_Reference/wp_send_json

  • Thanks mmm but I have that, my problem is that I don't want to pass the variable via the AJAX, I want to define it in the shortcode tag and retrieve it in the JSON, Can it be done? – stuporllama Feb 6 at 13:57
  • edit your question to explain why you want that because it's not comprehensible yet. – mmm Feb 6 at 14:11
  • My assumption is he wants a way to dynamically generate AJAX calls without writing additional code. Not a bad idea, but it creates overbloat imo. – Cam Feb 6 at 18:26
  • I understand how you want to do that but the question is "why ?". you send data from PHP to PHP on the same server then you don't need to use AJAX. – mmm Feb 6 at 20:02
  • @mmm What I want to do is way more complex, this is just the simplest example I could write to illustrate my problem. Imagine a quotation system where different customers have different rates, those rates can be pulled in by setting the customer name or id in the shortcode [myquoteplugin customer="mmm"] I could of course change the plugin output html to include hidden fields which get posted back to the AJAX function but I'd rather keep those values hidden in the back end hence wanting to use class varibles – stuporllama Feb 6 at 20:12

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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