This workshop is for you, if:
- You would like to know how Jquery and JSON work together
- You are trying to create series of dependent dropdowns based on data present in client side
Quick Introduction
A brief introduction of the two technologies used in this workshop are given below.
Jquery:
Jquery is a Javascript library. It provides useful functions for css and html elements manipulation. It has a weird }); syntax all over the place, but once you understand it, you can quickly develop the javascript stuffs with little pain. It serves as a wrapper over the basic javascript elements. It also provides a wrapper over the AJAX api. For more details visit http://www.jquery.com/. You can also download the latest Jquery library from their website.
JSON:
JSON which stands for JavaScript Object Notation, is a client side data structure to store and exchange data similar to XML. Check out our article on JSON for more details.
Requirements
We would like to create a series of dropdown for our website. The first dropdown will provide a list of sections (i.e. Java Programming and Market Analysis). On selecting, it should display another dropdown with list of categories (like Java Basics, JSP & Servlets etc). On selecting the category, it should display a bullet list of articles under this selection. We do not want our page to get refreshed on each select. However, for this example, we assume that we maintain the data in a static file in the client side instead fetching data from server side.
Solution
We identify and describe each element necessary for implementing the above mentioned requirement.
Data storage:
As per the requirement, we would like to store the data in a static file. We generally have three options viz. Properties file, XML file and JSON file. Since we need to handle everything from client side using Jquery, JSON would be the best bet.
We maintain two different json files.
- site_category.json - Maintains data related to sections and categories
- site_articles.json - Maintains the data related to categories and articles
The below code snippet shows a snapshot of the two JSON. We could have created single JSON for maintaining both the data. Also, we could have structured it in a different way, but our aim here is to understand the interaction of JSON with Jquery... so let us move on.
{
"java_programming": [
{
"ky": "java_basics", //Used for select options value to be passed
"val": "Java Basics" //Used for dropdown value to be displayed
},
{
"ky": "jsp_servlets",
"val": "JSP & Servlets"
},
{
"ky": "javascripts",
"val": "Javascripts"
}
],
...
{
"java_basics": ["Java Hello World - Tech Programmer", "Java Hello World using Eclipse IDE - Tech Programmer",
"Reading Java API documents - Tech Programmer",
"Common Java Exception and Error reference catalog - Tech Programmer"],
"jsp_servlets": ["First JSP/Servlet Workshop - Tech Programmer", "Integrating Eclipse with Tomcat - Tech Programmer",
"Session Based Shopping Cart - Tech Programmer"],
...
Web page
We need to create a simple html page in which all the action takes place. By action we mean, selecting one dropdown causing another dropdown to be displayed and so on. List of things to be done in this page are given below:
- Add three html div elements. Two for each dropdowns and one for the article list.
- Are we using Javascript? No. Don't we need to import some library? We are planning to use Jquery. We need to import Jquery library into the page. So, download and add a javascript link to it.
- We need to write the jquery code for performing all the on change action.
Let us go through each of the task in detail to finish off this workshop. Here we go....
1. Adding three html DIV elements
<div style="position: absolute; top: 50px; left: 5px">Section: <select id="section" name="section">
<option value="select">Select</option>
<option value="java_programming">Java Programming</option>
<option value="market_analysis">Market Analysis</option>
</select>
</div>
<div id="divCategory" style="position: absolute; top: 80px; left: 5px; display:none">
Category: <select id="category" name="category"></select>
</div>
<div id="divArticles" style="position: absolute; top: 120px; left: 5px; display:none">test
</div>
Note the last two DIV elements are marked as hidden for starters by setting the style as 'display:none'. Have you noticed the missing onChange on each of the select/options element? Not sure, how all these are going to work!
2. Adding link to Jquery library:
<script type="text/javascript" src="/static/jquery-1.3.1.js"></script>
We need to create a folder structure. We maintained the html as jquery_json.html in the root directory. We created a static folder inside it and add the jquery and JSON.
Wait there! There is no link added to json file. Interesting! The JSONs are not used directly as javascript variables. We will have Jquery look up for it and convert it into an object. Hang on, you will see.
3. Writing Jquery code:
Welcome to the fun side of this workshop!
We start by adding script tag in our page just the way we add for writing any javascript in page. We then use the jquery check for document readiness.
<script type="text/javascript">
$(document).ready( function() {
});
</script>
We write all the code inside the ready block. It checks, if the page is loaded in the browser completely before other events start firing. Get used to the }); syntax and you will start enjoying too!
Now, we need to write something which is similar to a javascript onChange. But the best part here is that you do not have to attach an onchange into your html select.
$("#section").change( function () {
}
The pound (#) symbol refers to the id attribute value of the html element. Jquery also provides option of accessing by class name of the element and element itself. Like $(€œ.class€) and $('div'). Refer to Jquery documentation (http://docs.jquery.com/) for more details.
Getting back to our example, all the code for on selection of a section should go inside the above change function.
We may have lots of logic but one thing worthwhile to look at is how the JSON is accessed from Jquery. See the snippet below:
$.getJSON("static/site_category.json", function(json) {
var catJson = json[sSec];//Fetch content for appropriate section
var options = "<option value=\"select\">Select</option>";//A variable which we build
for(i=0;i<catJson.length;i++) {//iterating contents for the selected section
options +="<option value=\""+catJson[i].ky+"\">"+catJson[i].val+"</option>";//generate option for each category
}
$("#category").html(options);//inject options into select tag
$("#divCategory").show();//Magic! show the category div
});
}
$getJSON is one of the functions in Jquery. It is basically an AJAX implementation. This means, you can also call a JSP, Servlet or PHP which returns a JSON object. Well, do not worry, it will not be left as homework. We will be writing another article with these details.
So, we are just pointing to the JSON and passing it a callback function. There are other parameters which can be passed into this function but we are only using two here. The callback function gets the JSON as a variable which we can have fun with. See the inline comments describing all the fun I've had with it.
On selection of category, a list of articles is displayed in the same way. The source is bundled into zip and can be downloaded by clicking here (jquery_json.zip).
You can check this stuff in action by accessing the link (Code in action).
This example is close to an AJAX based dropdown list. Once you understand this we would like to explain how we could use Jquery and JSON to access dynamic server side objects for generating subsequent dropdowns.
It is time for us to welcome Jquery, the Prince, who will be the next King to rule the client side world!