I have the following piece of Ajax which calls a php file which intends to return the HTML content of a shortcode.
The Ajax call looks like this :
var PostData = "Action=refresh-cart";
jQuery.ajax({
dataType: "text",
type: 'POST',
url : '<?php echo plugins_url( 'class-booking-system/class-booking-process.php', dirname(__FILE__) );?>',
cache: false,
data : PostData,
complete : function() { },
success: function(data) {
// jQuery("#loading-img").hide();
alert(data);
// jQuery("#join-class-div-3").html(data);
}
});
The PHP looks like this :
<?php
require_once( ABSPATH . '/wp-includes/shortcodes.php' );
if(isset($_POST['Action'])) {
$Action = $_POST['Action'];
if($Action == "refresh-cart") {
echo do_shortcode('[woocommerce_cart]');
}
}
?>
However when I call my Ajax method it returns an HTTP 500 - which I assume means the do_shortcode function was not found in this context. How can I give my plugin the ability to call this wordpress function via ajax?
I think you should take a look at the Codex article on using Ajax in Plugins. It provides a very good example on how to go about making ajax calls in WordPress.
Adapting their example to your code I get something like the following:
First we load the javascript. We also pass some javascript variables via
wp_localize_script
. In this case, we're going to pass the admin's URL for processing all ajax calls.Second, in our javascript we can make the ajax call and define our ajax "action" and any other data we need in the data object. Because "action" has kind of a different meaning, I've renamed your action to "refresh_cart".
Third, we need to set up the callback for our ajax action.
admin-ajax.php
looks through all of WordPress's pre-configured actions and then also looks for anything added to thewp_ajax_$my_action_name
on the back-end andwp_ajax_nopriv_$my_action_name
on the front-end. I am assuming your question concerns the front-end and since in thedata
object we setaction = my_action
the corresponding action hook would bewp_ajax_nopriv_my_action
... to which we have attached themy_action_callback
function. WordPress should be fully loaded and their shouldn't be an issue running shortcodes as far as I can tell.And voila! I think that should do it, but I have to warn you that I didn't test any of this, so use with prudence.