Shortcode does not exist in Ajax context

Support MB Views Shortcode does not exist in Ajax contextResolved

Viewing 11 posts - 1 through 11 (of 11 total)
  • Author
    Posts
  • #45947
    FabianFabian
    Participant

    I am trying to render a view in an Ajax call but it appears the mbv shortcode is not available to the context. The output I get from the code below is "Shortcode not found." The php function is hooked to plugins_loaded. Any idea how to get this working? Thank you.

    ob_start();
    while($ajaxposts->have_posts()) : $ajaxposts->the_post();
    	if (shortcode_exists('mbv')) {
                    echo do_shortcode('[mbv name="post-card"]');
                } else {
                    echo '<div>Shortcode not found.</div>';
                }
    endwhile;
    $response = ob_get_clean();
    #45958
    PeterPeter
    Moderator

    Hello,

    The hook plugins_loaded is fired before init which is the hook that fires all Meta Box functions. You can try to add your callback function to the action init with the priority later than 20 and see if it helps.

    Refer to this documentation https://docs.metabox.io/functions/rwmb-set-meta/

    #45970
    FabianFabian
    Participant

    Thank you, that is good to know. I changed to init with priority 100 but it still doesn't recognize the shortcode. Same for all other hooks I tried. Shortcodes from other plugins work as expected. I don't see anything in the MB docs related to this.

    #45971
    FabianFabian
    Participant

    (Also, the callback is triggered by a button click so I guess it shouldn't matter where it is inserted?)

    #45983
    PeterPeter
    Moderator

    Hello,

    Please share your site credentials by submitting this contact form https://metabox.io/contact/
    I will take a look.

    #45988
    FabianFabian
    Participant

    Thank you for investigating. I have sent you the login.

    #46051
    Gerard HalliganGerard Halligan
    Participant

    I have the same issue. Were you able to fix it?

    Thanks,
    Ger

    #46063
    PeterPeter
    Moderator

    Hello Ger,

    The issue happens because the view shortcode runs the frontend only. If you use Ajax, that means the shortcode is called in the admin area and it won't work.
    We've fixed that issue and it will be included in the new version of MB Views.

    #46065
    Gerard HalliganGerard Halligan
    Participant

    Hi Peter,

    In my case it is a form I want to insert by ajax through a MutationObserver, when a certain div is created.
    Whenever I try to call do_shortcode in the ajax call, it returns nothing. I tried to work around it by calling the shortcode in wp_loaded and saving the output to a transient. I thought this worked, as I was able to output the form when i got the transient value through the ajax call and output it in the right place on my page, but the form mustn't be fully initialised and parts of it don't work like the date picker, conditional logic.

    Could the fix you are working on for views also be a fix for forms?

    Thanks,
    Ger

    #46078
    PeterPeter
    Moderator

    You can try to apply the fix on your site and see how it goes. Here is the screenshot of the updated code https://imgur.com/gcDbOpP

    #46081
    Gerard HalliganGerard Halligan
    Participant

    Thanks Peter but the form still doesn't show?

    I updated the bootstrap file to the below

    $renderer = new Renderer( $meta_box_renderer );
    new Shortcode( $renderer );

    if ( is_admin() ) {
    $location = new Location\Settings;
    new Editor( $location );
    new ConditionalLogic;
    new AdminColumns;
    new Category;
    new Import;
    new Export;
    } else {

    new ActionLoader( $renderer );

    new TemplateLoader( 'singular' );
    new TemplateLoader( 'archive' );
    new TemplateLoader( 'code' );

    new ContentLoader( $renderer, 'singular' );
    new ContentLoader( $renderer, 'archive' );
    new ContentLoader( $renderer, 'code' );
    }

    This is my ajax code. you can ignore the references to transient. I just modified to see if the shortcode was working. The issue is that do_shortcode("[mb_frontend_form id='amelia-custom-field-group']"); returns ''?

    add_action('wp_ajax_insert_inss_mb_attendee_form', 'insert_inss_mb_attendee_form');
    add_action('wp_ajax_nopriv_insert_inss_mb_attendee_form', 'insert_inss_mb_attendee_form');
    function insert_inss_mb_attendee_form() {
        $output = do_shortcode("[mb_frontend_form id='amelia-custom-field-group']");
        //$output = get_transient('amelia_custom_field_group_output');
        
        if ($output === false) {
            error_log(__METHOD__ . " Transient not found or expired");
            echo '<p>No output from shortcode.</p>';
        } elseif ($output === '') {
            error_log(__METHOD__ . " No output from shortcode");
        } else {
            echo $output;
        }
        wp_die(); // This is required to terminate immediately and return a proper response
    }

    js ajax call

    function callInsertMBInssOrderForm(bookingCostDiv) {
        // Check if the div with class 'rwmb-meta-box inss_custom_fields' exists
        if (bookingCostDiv.querySelector('.inss_custom_fields')) {
            return; // Exit the function if the div exists
        }
    
        fetch(<code>${ajaxurl}?action=insert_inss_mb_attendee_form</code>, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({})
        })
        .then(response => response.text())
        .then(mbOrderForm => {
            // Append the response data (shortcode HTML) to the start of the div with class am-custom-fields
            const customFieldsDiv = bookingCostDiv.querySelector('.am-custom-fields');
            if (customFieldsDiv) {
                if (customFieldsDiv.querySelector('.inss_custom_fields')) {
                    return;
                }       
                customFieldsDiv.insertAdjacentHTML('afterbegin', mbOrderForm);
    
                handleMetaboxGroupCloning(customFieldsDiv, numberOfPeople)
            } else {
                console.error('Error: .am-custom-fields element not found');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }
Viewing 11 posts - 1 through 11 (of 11 total)
  • You must be logged in to reply to this topic.