我将以下代码定义为简码。这是一个调查应用程序。当我使用仪表板子菜单中的短代码时,它显示并运行良好。但就像我尝试从前端使用它一样,表单正在显示,但按钮没有触发。我不明白问题出在哪里。我已经分享了我的代码。你能告诉我问题出在哪里吗?
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">
<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); ?>">Submit</button>
</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.');
},
});
});
});
我没有看到 JS 被加载到哪里。 您可以从短代码函数中对 JavaScript 资源进行排队,以确保它们被加载到使用短代码的任何屏幕上,或者将其包含在标签中