Creating Dynamic Dropdowns in Moodle Forms with AJAX

Moodle development often presents unique challenges, and one common request involves creating dynamic dropdown lists within forms. Specifically, users often want a second dropdown list to populate its options based on the selection made in a first dropdown, all without reloading the entire page. This is where AJAX comes in.

This post will walk you through the process of implementing such a feature in a Moodle form, using a local plugin and AJAX to seamlessly update content from the database.

The Problem: Static Dropdowns and User Experience

Imagine a scenario where you have a dropdown list of courses, and you want to display the teachers associated with the selected course in a second dropdown. Without dynamic loading, you’d have to submit the form, reload the page, and then update the second dropdown based on the server response. This creates a clunky and inefficient user experience.

The Solution: AJAX to the Rescue

Our approach leverages AJAX (Asynchronous JavaScript and XML) to communicate with the server in the background, fetching the relevant data for the second dropdown without a full page refresh. Here’s a demo of it in action:

I’ve created a local Moodle plugin called “ajax_demo.” Within this plugin, I’ve set up a form with two dropdowns. The first dropdown lists available courses on the Moodle server. When a user selects a course, the second dropdown dynamically populates with the teachers assigned to that specific course.

For instance, if I select “Test Course One,” the second dropdown immediately displays “Test Teacher.” If I choose “Ricoshae 3.9,” the second dropdown remains empty because that course currently has no assigned teachers. The key here is that this all happens instantly, without any page reload. While the demo doesn’t currently handle saving the selected values, in a real-world scenario, you would integrate this functionality.