JSON: A Real World Example: Fill A Drop Down List
January 13th, 2010In my previous article on a simple introduction to JSON I showed how to use JSON to post back to the server, do some calculations and respond with the results rendered in the browser. In this example I will show you a real world example where you can select from a first option list and dynamically populate a second drop down list with items.
Requirements
- A basic knowledge of HTML and PHP
- Basic knowledge of jQuery assumed
Demo
To begin with download jQuery and start the basic html page with the page structure and a link to the jQuery library. We will use the built in post method within jQuery to post to the server and retrieve the results given from the PHP script.
<!DOCTYPE html >
< html >
<head>
<title>JSON: A Real World Example</title>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
</body>
</ html >
Now on our page we are going to have two drop down lists. The first will be our primary option list which will be pre-populated with values. The second will not have any values to start with but will instead be populated via an AJAX request depending on which option is selected in the primary option list.
Put the following drop down lists into the body section of the page:
<select name="primary_select" id="primary_select">
<option value="0">select an option</option>
<option value="1">option one</option>
<option value="2">option two</option>
<option value="3">option three</option>
</select>
<select name="secondary_select" id="secondary_select">
</select>
Before we code any javascript or PHP we should really hide the secondary options list from the user before they select from the first list. Add this line of CSS to hide the secondary drop down list:
<style type="text/css">
#secondary_select {display: none;}
</style>
Ok, now we are ready for some jQuery. We’ll start by capturing the change event of the primary option list. Every time a user selects a different option from the list the code will execute. Within this code block we want to post the value of the selected option in the primary option list. we can get this value using the val property of the option list as shown below:
<script type="text/javascript">
$("#primary_select").change(function () {
$.post("dynamicselect.php",
{
primary_select : $('#primary_select').val(),
},
function(data){
}, "json");
});
</script>
We’ve posted our selected value to the PHP script named dynamicselect.php and have set up the second argument of the post method ready to capture the response from the PHP script. We’ll come back to the results and how to populate the second list shortly. Let’s first get into some PHP.
In one go here is all the PHP code we need:
$selected_option = $_POST['primary_select'];
if ($selected_option == 0) {
$options = '';
} elseif ($selected_option == 1) {
$options = array(
'option one a' => 'option one a',
'option one b' => 'option one b',
'option one c' => 'option one c',
'option one d' => 'option one d',
);
} elseif ($selected_option == 2) {
$options = array(
'option two a' => 'option two a',
'option two b' => 'option two b',
'option two c' => 'option two c',
'option two d' => 'option two d',
);
} elseif ($selected_option == 3) {
$options = array(
'option three a' => 'option three a',
'option three b' => 'option three b',
'option three c' => 'option three c',
'option three d' => 'option three d',
);
}
$array = array('options' => $options);
echo json_encode($options);
Here’s an explanation of what I did in the PHP code. We can capture the value of the selected item in the primary drop down list and assign it to a local variable using this line:
$selected_option = $_POST['primary_select'];
The next section of code checks to see if the selected item’s value is equal to 0, 1, 2 or 3. Depending on the results it assigns another variable, $options, with an array. This array is a two dimensional array that we will send back to our page and assign the name and value pairs to the secondary drop down list. In this case I have simply hard coded in some values but this script could easily be amended to fetch results from a database XML file or elsewhere to assign values to the array.
In the last two lines we create a new array to hold the current array, encode the array with the json_encode function and print the results to the page. This is then retrieved in the browser via javascript.
$array = array('options' => $options);
echo json_encode($options);
Back in our javascript the our function is waiting for the results:
function(data){
$('#secondary_select').show();
$('#secondary_select').empty();
$.each(data, function(val, text) {
$('#secondary_select').append(
$('<option></option>').val(val).html(text)
);
});
Since we made our second drop down list invisible we’ll first use jQuery to show the option list on the page.
$('#secondary_select').show();
Each time this code runs it will append options to the select element. So that we don’t just add to what is already there we want to first of all empty all contents of the select element.
$('#secondary_select').empty();
Then using jQuery we can loop through our array that we sent from PHP appending an option each time we run through the loop.
$.each(data, function(val, text) {
$('#secondary_select').append(
$('<option></option>').val(val).html(text)
);
And that’s it! When a user chooses from the first option list the second option list is displayed on the page and values are dynamically added to the list from values defined in the PHP script. The full javascript code is shown below:
$("#primary_select").change(function () {
$.post("dynamicselect.php",
{
primary_select : $('#primary_select').val(),
},
function(data){
$('#secondary_select').show();
$('#secondary_select').empty();
$.each(data, function(val, text) {
$('#secondary_select').append(
$('<option></option>').val(val).html(text)
);
});
}, "json");
});




January 14th, 2010 at 2:15 am
Thanks for the lesson Adam. I am going to ask questions about your tutorial that I don’t understand.
1) What is the purpose of the line “$array = array(’options’ => $options);” in the dynamicselect.php file since it is not used and the code seems to work without it.
2) In the javascript “function(data)” how is data used to signify or how is it know that this has the information that needs to be worked on by the function?
3) How is the line “ $(”).val(val).html(text)” parsed correctly in the second select when the syntax for a select should be, as used in the primary_select, “select an option”. It works correctly but I don’t see how it is changed to the correct order.
Thanks again for helping me learn this
WBR
January 19th, 2010 at 7:50 pm
Hi William,
Let me try to answer your questions:
1. Yep, looks like I left that in by mistake. There’s actually no need for this line. I was intending to pass multiple arrays via JSON but decided to keep it simple in this tutorial so it will work perfectly well without that line.
2. I believe that this is built into jQuery. There is no need for the variable to be called data, it should work with anything you like if you want to call it something more meaningful.
3. Sorry, not too sure what you are asking here. I’m happy to help out if you want to contact me on twitter though @mind_revolution
January 21st, 2010 at 4:17 pm
What I meant is that you would think this line:
$(”).val(val).html(text)
Would print out:
” option three a”
from the sequence of the statement, but it does not.
February 2nd, 2010 at 7:26 pm
Hi. Very interesting site. I found it on Bing. I will definately recommend it to my friends. Please keep up the great work.
March 8th, 2010 at 10:53 pm
Hey! This is not that simple! In fact it’s quite complicated.
Here is another complicated json/php tutorial
http://codediaries.blogspot.com/2010/02/complete-php-curl-and-json-and-google.html