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"}
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.