do_shortcode inside AJAX callback

The How

It would be much better and easier if you’d just add the script directly to the main body instead of the AJAX call.

The same goes with the shortcode result. Just use the shortcode as argument inside wp_localize_script():

wp_localize_script( 'script-handle', 'pluginObject', array(
    'contactForm' => do_shortcode( '[contact-form-7 id="698" title="Meet The Team Email"]' ),
) );

Then – inside your jQuery AJAX handler, do whatever you need to do – for e.g. insert the Contact Form.

( function( $, plugin ) {
    $.ajax( {
        url  : plugin.ajaxurl,
        data : {
            action         : plugin.action,
            _ajax_nonce    : plugin._ajax_nonce,
            data           : { 
                plugin.contactForm 
            }
        },
        beforeSend : function( d ) {
            console.log( 'Before send', d );
        }
    } )
        .done( function( response, textStatus, jqXHR ) {
            console.log( 'AJAX done', textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
            // this.processAJAXResponse( response );
        } )
        .fail( function( jqXHR, textStatus, errorThrown ) {
            console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
        } )
        .then( function( jqXHR, textStatus, errorThrown ) {
            console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
        } );
} )( jQuery, pluginObject || {} );

You now should have access to the rendered Form inside your AJAX callback, but as well inside your JavaScript AJAX handler.

The Why

IIRC your problem is that AJAX requests are always admin requests – even when public. And as there’s no output of shortcodes on admin pages, there’s nothing than a string return value as well.

Rule: Never try to run shortcodes inside AJAX or Admin requests.

Additional notes:

  • Don’t add scripts inside AJAX callbacks. That’s simply not the right thing to do. Pass values – as I explained above – using wp_localize_script().
  • A shortcode normally is just a wrapper for some API. Never use the shortcode – use the APi instead. Greetings from Stephen Harris who just told me in chat that I should point you at that.

Leave a Comment