Get returned variable from a function to add_shortcode function

You can’t put AJAX into the callback for a shortcode. It doesn’t make any sense to. If you’re making an AJAX request then you’re making it on the front-end and the shortcode has already rendered.

So anything you do with the response to the AJAX request needs to occur on the front-end. So what you need to do is output some HTML in the shortcode with a class or ID that your JavaScript can use to populate the data on the front-end.

So your shortcode could look like this:

function timezone(){
    echo '<div class="timezone"></div>';
}

Then your AJAX request should populate that div with the response on completion:

$.post(MyAjax.ajaxurl, data, function(response) {
    $('.timezone').html( response );
});

In that example we’re using jQuery to set the HTML of that div to the value of the response.

If you want the shortcode to have a default value, then one approach would be to abstract out the function responsible for the output into its own function. Then just use that same function inside both the AJAX callback and the shortcode callback.

So lets create a function for outputting the text:

function wpse_301294_whatever() {
    return 'Whatever';
}

That function will return the string Whatever.

Then we can update the shortcode to use this function within the div:

function timezone(){
    echo '<div class="timezone">' . wpse_301294_whatever() . '</div>';
}

And the AJAX callback:

function my_action_callback() {
    echo wpse_301294_whatever();
    wp_die();
}

Now you have a function, wpse_301294_whatever(), responsible for outputting something, as well as a Shortcode and AJAX callback that can use that output in different contexts.

Leave a Comment