UPDATE: I’ve updated this post with a more comprehensive walkthrough, more code examples, and a downloadable archive that contains all the relevant files. It’s located here: More AJAX Dropdowns with CodeIgniter
CodeIgniter is my first choice for PHP rapid development frameworks. It’s lightweight, powerful, and easy to use. However there are a few common tasks that are not documented as well as they could be. For instance, populating the options in a dropdown select field using AJAX is certainly possible, but you’ll search long and hard before finding a good tutorial or a recipe for actually doing it.
While creating a dynamic form for a client’s project database, I had to figure out how to query the database using AJAX and populate several form fields based on the results of that query. So, for posterity’s sake, I’ve decided to document exactly how I accomplished it. First of all, this method uses CodeIgniter version 1.7.3. For the AJAX functionality, I use jQuery version 1.4.2. The database is MySQL with InnoDB tables.
Now, the application that I’m discussing here is basically a project management app with CRM functions. For this specific form, the user has to assign a “Client” to a project. Based on which Client is assigned, the user can choose a “Contact” for the project. So, the initial form is loaded with all “Clients” who already exist in the database (A future post will detail how I handle dynamically adding a new Client from the form). When the user chooses a Client from the “Client” dropdown, an AJAX request is made to the CodeIgniter controller to retrieve all of the contacts associated with that Client. The AJAX response is then used to populate the “Contacts” dropdown.