jQuery Module Not Loading on Click from Module Buttons

I am working on a WordPress project where I have a set of modules that should load dynamically when clicking on module buttons. However, the modules are not loading as expected. Below is the relevant code:

single-coure.php

<div class='course_wrap container_wrap container_wrap_first main_color sidebar_left'>
    <div class='container'>
        <main id="course-content" class='template-page template-course content <?php avia_layout_class('content'); ?> units' <?php avia_markup_helper(array('context' => 'content', 'post_type' => 'course')); ?>>
            <div id="module-content-wrap">
                <?php
                if (have_posts()) {
                    while (have_posts()) {
                        the_post();
                        the_content();
                    }
                }

                // Fetch related modules
                $course_id = get_the_ID();

                // Query to get modules related to the course
                $args = array(
                    'post_type' => 'module',
                    'meta_query' => array(
                        array(
                            'key' => 'module_course',
                            'value' => $course_id,
                            'compare' => '='
                        )
                    ),
                    'posts_per_page' => -1
                );
                $course_modules = new WP_Query($args);

                // Initialize array to hold modules by type
                $modules = array(
                    'Course Overview' => array(),
                    'Welcome' => array(),
                    'Course Video' => array(),
                    'Quiz Questions' => array(),
                    'Next Steps' => array()
                );

                // Loop through modules and categorize them
                if ($course_modules->have_posts()) {
                    while ($course_modules->have_posts()) {
                        $course_modules->the_post();
                        $module_id = get_the_ID();

                        // Get module type, title, and content
                        $module_types = maybe_unserialize(get_post_meta($module_id, '_module_types', true));
                        $module_title = get_post_meta($module_id, 'module_title', true); // Fetch the specific module section title
                        $module_content = get_post_meta($module_id, 'module_content', true); // Fetch the specific module section content

                        // Fallback to default content types
                        $course_overview_content = get_post_meta($module_id, 'course_overview_content', true);
                        $welcome_content = get_post_meta($module_id, 'welcome_content', true);
                        $course_video_content = get_post_meta($module_id, 'course_video_content', true);
                        $quiz_questions_content = get_post_meta($module_id, 'quiz_questions_content', true);
                        $next_steps_content = get_post_meta($module_id, 'next_steps_content', true);

                        // Use specific content based on module type
                        if (empty($module_content)) {
                            if (!empty($course_overview_content)) {
                                $module_content = apply_filters('the_content', $course_overview_content);
                            } elseif (!empty($welcome_content)) {
                                $module_content = apply_filters('the_content', $welcome_content);
                            } elseif (!empty($course_video_content)) {
                                $module_content = apply_filters('the_content', $course_video_content);
                            } elseif (!empty($quiz_questions_content)) {
                                $module_content = apply_filters('the_content', $quiz_questions_content);
                            } elseif (!empty($next_steps_content)) {
                                $module_content = apply_filters('the_content', $next_steps_content);
                            } else {
                                $module_content = '<p>No content available for this module.</p>';
                            }
                        }

                        // Assign content to the correct module section
                        if ($module_types && is_array($module_types)) {
                            foreach ($module_types as $module_type) {
                                if (isset($modules[$module_type])) {
                                    $modules[$module_type][] = array(
                                        'slug' => get_post_field('post_name', $module_id),
                                        'title' => !empty($module_title) ? $module_title : get_the_title(),
                                        'content' => $module_content // Assign the correct content based on the module type
                                    );
                                }
                            }
                        }
                    }
                }

                wp_reset_postdata();

                // Display the modules
                $isFirstModule = true;

foreach ($modules as $moduleType => $moduleList) {
    if (!empty($moduleList)) {
        echo '<section class="module_wrap_section">';
        echo '<div class="module_wrap">';
        echo '<div class="module_inner">';
        echo '<div class="module_inner_header">';
        echo '<h2>' . esc_html($moduleType) . '</h2>'; // Display the module type as a section header
        echo '</div>';

        foreach ($moduleList as $module) {
            if ($isFirstModule) {
                // Display the content for the first module
                echo '<div class="module_inner_content">';
                echo '<div class="module_content">' . $module['content'] . '</div>';
                echo '</div>';
                $isFirstModule = false; // Set to false after loading the first module
            } else {
                // Display the content for other modules
                echo '<div class="module_inner_content">';
                echo '<div class="module_content">' . $module['content'] . '</div>';
                echo '</div>';
            }
        }
        echo '</div>';
        echo '</div>';
        echo '</section>';
    }
}

                ?>
            </div>
        </main>

        <aside class='sidebar units <?php avia_layout_class('sidebar'); ?>' role="complementary" itemscope="itemscope" itemtype="https://schema.org/WPSideBar">
            <div class="module_menu">
                <div class="course-title">
                    <h1><?php the_title(); ?></h1>
                </div>
                <div class='inner_sidebar'>
                    <ul id="module-links">
                        <?php
                        $icons = array(
                            'Course Overview' => 'fas fa-book-open',
                            'Welcome' => 'fas fa-handshake',
                            'Course Video' => 'fas fa-video',
                            'Quiz Questions' => 'fas fa-question-circle',
                            'Next Steps' => 'fas fa-tasks'
                        );

                        $order = ['Course Overview', 'Welcome', 'Course Video', 'Quiz Questions', 'Next Steps'];

foreach ($order as $type) {
    if (!empty($modules[$type])) {
        if ($type == 'Course Overview' || $type == 'Welcome' || count($modules[$type]) == 1) {
            $item = $modules[$type][0];
            $icon = isset($icons[$type]) ? $icons[$type] : 'fas fa-file';
            echo '<li>';
            echo '<a href="#" data-module="' . esc_attr($item['slug']) . '" data-course-id="' . esc_attr($course_id) . '"><i class="' . esc_attr($icon) . '"></i> ' . esc_html($type) . '</a>'; // Display correct title
            echo '</li>';
        } else {
            echo '<li class="dropdown">';
            $icon = isset($icons[$type]) ? $icons[$type] : 'fas fa-file';
            echo '<a href="#" class="dropdown-toggle"><i class="' . esc_attr($icon) . '"></i> ' . esc_html($type) . '</a>';
            echo '<ul class="dropdown-menu">';
            foreach ($modules[$type] as $item) {
                echo '<li><a href="#" data-module="' . esc_attr($item['slug']) . '" data-course-id="' . esc_attr($course_id) . '">' . esc_html($item['title']) . '</a></li>'; // Display correct title
            }
            echo '</ul>';
            echo '</li>';
        }
    }
}

                        ?>
                    </ul>
                </div>
            </div>
        </aside>
    </div><!-- end container -->

    <div class="module_bottom_bar">
        <div class="module_bottom_bar_buttons">
            <div id="next-module-container">
                <button id="prev-module">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" class="main-grid-item-icon" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
                        <polygon points="19 4 9 12 19 20 19 4" />
                        <line x1="5" x2="5" y1="5" y2="19" />
                    </svg>
                    <span>Previous</span>
                </button>
                <button id="next-module">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" class="main-grid-item-icon" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
                        <polygon points="5 4 15 12 5 20 5 4" />
                        <line x1="19" x2="19" y1="5" y2="19" />
                    </svg>
                    <span>Next</span>
                </button>
            </div>
        </div>
    </div>
</div><!-- end course_wrap -->

<?php
get_footer();
?>

<script>
jQuery(document).ready(function($) {
    var modules = <?php echo json_encode($modules); ?>;
    var moduleOrder = [];

    // Flatten the modules array to get a list of modules in the order they are displayed
    $.each(modules, function(type, moduleGroup) {
        $.each(moduleGroup, function(index, module) {
            moduleOrder.push({
                slug: module.slug,
                content: module.content
            });
        });
    });

    var currentModuleIndex = 0;

    function loadModule(moduleSlug) {
        $('#module-content-wrap').html('<div class="loading-indicator">Loading module...</div>');

        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'POST',
            data: {
                action: 'load_module_content',
                nonce: '<?php echo wp_create_nonce('rp_ajax_nonce'); ?>',
                module: moduleSlug
            },
            success: function(response) {
                if (response.success) {
                    $('#module-content-wrap').html(response.data.content);
                } else {
                    console.error('Error loading module content:', response.data.message);
                    $('#module-content-wrap').html('<p>Error loading module content. Please try again later.</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', error);
                $('#module-content-wrap').html('<p>An unexpected error occurred while loading the module. Please try again later.</p>');
            }
        });
    }

    // Initial load of the first module
    loadModule(moduleOrder[currentModuleIndex].slug);

    // Handle sidebar link clicks
    $('#module-links a').on('click', function(e) {
        e.preventDefault();
        var moduleSlug = $(this).data('module');
        currentModuleIndex = moduleOrder.findIndex(module => module.slug === moduleSlug);
        loadModule(moduleOrder[currentModuleIndex].slug);
    });

    // Handle Next and Previous button clicks
    $('#next-module').on('click', function(e) {
        e.preventDefault();
        currentModuleIndex++;
        if (currentModuleIndex >= moduleOrder.length) {
            currentModuleIndex = 0; // Loop back to the first module
        }
        loadModule(moduleOrder[currentModuleIndex].slug);
    });

    $('#prev-module').on('click', function(e) {
        e.preventDefault();
        currentModuleIndex--;
        if (currentModuleIndex < 0) {
            currentModuleIndex = moduleOrder.length - 1; // Loop back to the last module
        }
        loadModule(moduleOrder[currentModuleIndex].slug);
    });
});
</script>

functions.php

function get_module_content($module_id)
{
    $module_content = get_post_meta($module_id, 'module_content', true);

    // Check if content is empty
    if (empty($module_content)) {
        return ''; // Or handle empty content as needed
    }

    // Basic formatting or filtering can be done here
    return apply_filters('the_content', $module_content);
}

function load_first_module($modules)
{
    $priority_order = ['Course Overview', 'Welcome', 'Course Video', 'Quiz Questions', 'Next Steps'];

    foreach ($priority_order as $module_type) {
        if (isset($modules[$module_type]) && !empty($modules[$module_type])) {
            $first_module = $modules[$module_type][0]; // Load the first available module of this type
            load_module($first_module['slug'], $first_module['course_id']);
            return;
        }
    }
}

function load_module_content()
{
    check_ajax_referer('rp_ajax_nonce', 'nonce');

    $module_slug = sanitize_text_field($_POST['module']);

    $args = array(
        'name' => $module_slug,
        'post_type' => 'module',
        'posts_per_page' => 1
    );

    $module_query = new WP_Query($args);

    if ($module_query->have_posts()) {
        $module_query->the_post();
        $module_id = get_the_ID();
        $module_content = apply_filters('the_content', get_post_meta($module_id, 'module_content', true));

        wp_send_json_success(array(
            'content' => $module_content
        ));
    } else {
        wp_send_json_error(array('message' => 'Module not found.'));
    }

    wp_die();
}
add_action('wp_ajax_load_module_content', 'load_module_content');
add_action('wp_ajax_nopriv_load_module_content', 'load_module_content');

function load_module_content_callback()
{
    if (!isset($_GET['module'])) {
        wp_send_json_error(['error' => 'No module specified.']);
    }

    $module_slug = sanitize_text_field($_GET['module']);
    $module_post = get_page_by_path($module_slug, OBJECT, 'module');

    if (!$module_post) {
        wp_send_json_error(['error' => 'Module not found.']);
    }

    $module_id = $module_post->ID;
    $module_title = get_the_title($module_id);
    $module_content = apply_filters('the_content', $module_post->post_content);

    $featured_image = get_the_post_thumbnail($module_id, 'full');

    $response = [
        'title' => $module_title,
        'content' => $module_content,
        'featured_image' => $featured_image ? $featured_image : ''
    ];

    wp_send_json_success($response);
}

add_action('wp_ajax_load_module_content', 'load_module_content_callback');
add_action('wp_ajax_nopriv_load_module_content', 'load_module_content_callback');


function display_module_section($module_type, $module_id, $video_labels)
{
    switch ($module_type) {
        case 'course_overview':
        case 'welcome':
        case 'quiz_questions':
        case 'next_steps':
            echo '<h2>' . esc_html(ucwords(str_replace('_', ' ', $module_type))) . '</h2>';
            echo apply_filters('the_content', get_post_meta($module_id, $module_type . '_content', true));
            break;

        case 'course_video':
            echo '<h2>Course Videos</h2>';
            if (!empty($video_labels)) {
                // ... existing code for displaying video labels ...
            } else {
                // Handle case where there are no video labels but the module type is 'course_video'
                $module_content = get_post_meta($module_id, 'course_video_content', true);
                if (!empty($module_content)) {
                    echo '<div class="module_content">' . apply_filters('the_content', $module_content) . '</div>';
                } else {
                    // Handle empty content for course video
                }
            }
            break;

        default:
            echo '<p>Invalid module type.</p>';
            break;
    }
}

function handle_module_loading()
{
    $course_id = isset($_POST['course_id']) ? intval($_POST['course_id']) : 0;

    if ($course_id) {
        $modules = get_course_modules($course_id);

        if (!empty($modules)) {
            // Process and return the modules
            wp_send_json_success(array('modules' => $modules));
        } else {
            wp_send_json_error('No modules found for this course.');
        }
    } else {
        wp_send_json_error('Invalid course ID.');
    }
}
add_action('wp_ajax_load_modules', 'handle_module_loading');
add_action('wp_ajax_nopriv_load_modules', 'handle_module_loading');

Problem: The modules are not loading when I click on the module buttons. I have checked the console for errors and found the following message: “Error loading module content: No content found for this module.”

What I’ve Tried:

Verified that the module slugs are correct.
Ensured that the AJAX request is being sent and received.
Checked the PHP function to ensure it is returning the correct content.
Question: What could be causing the modules not to load on click, and how can I fix this issue?

Any help would be greatly appreciated. Thank you!