Shortcode does not exist in Ajax context
- This topic has 10 replies, 3 voices, and was last updated 9 months, 1 week ago by
Gerard Halligan.
-
AuthorPosts
-
July 19, 2024 at 7:01 PM #45947
Fabian
ParticipantI 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();
July 21, 2024 at 3:41 PM #45958Peter
ModeratorHello,
The hook
plugins_loaded
is fired beforeinit
which is the hook that fires all Meta Box functions. You can try to add your callback function to the actioninit
with the priority later than 20 and see if it helps.Refer to this documentation https://docs.metabox.io/functions/rwmb-set-meta/
July 22, 2024 at 6:24 PM #45970Fabian
ParticipantThank 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.
July 22, 2024 at 6:53 PM #45971Fabian
Participant(Also, the callback is triggered by a button click so I guess it shouldn't matter where it is inserted?)
July 23, 2024 at 9:17 PM #45983Peter
ModeratorHello,
Please share your site credentials by submitting this contact form https://metabox.io/contact/
I will take a look.July 23, 2024 at 10:50 PM #45988Fabian
ParticipantThank you for investigating. I have sent you the login.
July 30, 2024 at 8:56 PM #46051Gerard Halligan
ParticipantI have the same issue. Were you able to fix it?
Thanks,
GerJuly 31, 2024 at 9:51 PM #46063Peter
ModeratorHello 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.July 31, 2024 at 10:27 PM #46065Gerard Halligan
ParticipantHi 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,
GerAugust 1, 2024 at 9:40 PM #46078Peter
ModeratorYou 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
August 1, 2024 at 10:45 PM #46081Gerard Halligan
ParticipantThanks 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); }); }
-
AuthorPosts
- You must be logged in to reply to this topic.