Tech-Freaks.in

Technically Driven To Perfection!

  • Increase font size
  • Default font size
  • Decrease font size
Home Javascripts Using Jquery with JSON - Jquery Coding

Using Jquery with JSON - Jquery Coding

E-mail Print
Article Index
Using Jquery with JSON
Jquery Coding
All Pages

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:

  1. Add three html div elements. Two for each dropdowns and one for the article list.
  2. 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.
  3. 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!


Add your comment

Your name:
Subject:
Comment:


Last Updated on Sunday, 21 June 2009 22:14