-
Evans hat einen Beitrag veröffentlicht
Problem mit nicht funktionierendem Shortcode im Frontend
Ich habe einen benutzerdefinierten Shortcode für eine Umfrageanwendung erstellt. Wenn ich den Shortcode im Untermenü des Dashboards verwende, funktioniert alles perfekt - das Formular wird angezeigt und die Schaltfläche wird wie erwartet ausgelöst.
However, when I try to use the same shortcode on the frontend, while the form is displayed, the button does not function properly (it doesn’t trigger any action).
I have already shared my code and cannot figure out where the issue lies. Could you help identify the problem?😅
class Class_frontend { public function __construct() { add_shortcode('greeting', [$this, 'display_survey']); } public function display_survey() { global $wpdb; $current_user_id = get_current_user_id(); $table_name = $wpdb->prefix . 'code_survey'; $query = "SELECT * FROM $table_name ORDER BY id DESC LIMIT 1"; $results = $wpdb->get_results($query); if (!empty($results)) { ob_start(); foreach ($results as $result) { ?> <form id="survey-form" action=""> <input type="radio" id="answer_1" name="surveypool" value="<?php echo esc_attr($result->question_1); ?>" /> <label for="answer_1"><?php echo esc_html($result->question_1); ?></label><br /> <input type="radio" id="answer_2" name="surveypool" value="<?php echo esc_attr($result->question_2); ?>" /> <label for="answer_2"><?php echo esc_html($result->question_2); ?></label><br /> <input type="radio" id="answer_3" name="surveypool" value="<?php echo esc_attr($result->question_3); ?>" /> <label for="answer_3"><?php echo esc_html($result->question_3); ?></label><br /> <input type="radio" id="answer_4" name="surveypool" value="<?php echo esc_attr($result->question_4); ?>" /> <label for="answer_4"><?php echo esc_html($result->question_4); ?></label><br /> <button type="button" id="generate_button" data-survey-id="<?php echo esc_attr($result->id); ?>">Einreichen</button> <input type="hidden" name="trp-form-language" value="de"/></form> <?php } return ob_get_clean(); } return '<p>No survey available.</p>'; // Fallback message if no data is found. }
Javascript
jQuery(document).ready(function ($) { jQuery('#generate_button').on('click', function () { alert('working'); // Debugging step const selectedAnswer = jQuery('input[name="surveypool"]:checked').val(); const surveyId = jQuery(this).data('survey-id'); // Correct attribute selection if (!selectedAnswer) { alert('Please select an option.'); return; } jQuery.ajax({ url: ajax_ob.ajax_url, type: 'POST', dataType: 'json', data: { action: 'submit_survey', answer: selectedAnswer, survey_id: surveyId, user_id: ajax_ob.user_id, }, success: function (response) { if (response.success) { alert(response.data); $('#survey-form').remove(); // Optionally hide form after submission } else { alert(response.data); } }, error: function () { alert('An error occurred. Please try again.'); }, }); }); });