Probably the most popular post in the history of this blog is “Populate DropDowns with jQuery and Codeigniter”. In that post, I gave a quick overview of how to set up a dropdown or select box that depends on the value selected in another form element. That post was never really intended to be a complete “How To”, but it’s been such a popular post that I wanted to revisit the idea, and write up a more complete discussion of this technique.
What I’m going to do here is to create and populate an HTML select element using values that are dependent on a selection in another HTML input. In this case, I’m using two select elements, but you could adapt the technique for any kind of input. For example, let’s say you have a form that displays data for a zip code. Now, there are a LOT of zip codes in the US, and you probably don’t want to make your users scroll through such a long list to choose the value they’re interested in. So, you add another HTML select element that allows the user to choose the specific state that contains the zip code. So, initially, the zip code select element is blank, or set to some default value. Then once the user chooses a state, the zip code element is populated with all of the zip codes for that state. Nice, huh?
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.