{"id":79,"date":"2009-02-23T02:52:32","date_gmt":"2009-02-23T02:52:32","guid":{"rendered":"http:\/\/localhost\/tfcom_wp\/2009\/02\/23\/jquery-json\/"},"modified":"2009-02-23T02:52:32","modified_gmt":"2009-02-23T02:52:32","slug":"jquery-json","status":"publish","type":"post","link":"https:\/\/www.tech-freaks.com\/java\/javascript\/jquery-json.html","title":{"rendered":"Using Jquery with JSON"},"content":{"rendered":"<p>This workshop is for you, if:<\/p>\n<ul>\n<li>You would like to know how Jquery and JSON work together<\/li>\n<li>You are trying to create series of dependent dropdowns based on data present in client side<\/li>\n<\/ul>\n<p><strong>Quick Introduction<\/strong><br \/>A\u00a0brief introduction of the two technologies used in this workshop are given below.<\/p>\n<p align=\"justify\"><em>Jquery:<\/em><br \/>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\u00a0<a title=\"Jquery website\" href=\"http:\/\/www.jquery.com\/\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http:\/\/www.jquery.com\/<\/a>. You can also download the latest Jquery library from their website.<\/p>\n<p><em>JSON:<\/em><br \/>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\u00a0<a title=\"JSON with Javascript\" href=\"Java-Programming\/Javascripts\/json-javascript.html\" target=\"_blank\" rel=\"noopener noreferrer\">JSON<\/a>\u00a0for more details.<\/p>\n<p><strong>Requirements<\/strong><\/p>\n<p align=\"justify\">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 &amp; 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.<\/p>\n<p><strong>Solution<\/strong><\/p>\n<p>We identify and describe each element necessary for implementing the above mentioned requirement.<\/p>\n<p><strong>Data storage:<\/strong><br \/>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.<\/p>\n<p>We maintain two different json files.<\/p>\n<ul>\n<li>site_category.json &#8211;\u00a0 Maintains data related to sections and categories<\/li>\n<li>site_articles.json &#8211;\u00a0 Maintains the data related to categories and articles<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p>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&#8230; so let us move on.<\/p>\n<pre class=\"language-javascript\"><code>{\r\n  \"java_programming\": [\r\n    {\r\n      \"ky\": \"java_basics\", \/\/Used for select options value to be passed\r\n      \"val\": \"Java Basics\" \/\/Used for dropdown value to be displayed\r\n    \r\n    },\r\n    {\r\n      \"ky\": \"jsp_servlets\",\r\n      \"val\": \"JSP &amp; Servlets\"\r\n    },\r\n    {\r\n      \"ky\": \"javascripts\",\r\n      \"val\": \"Javascripts\"\r\n    }\r\n  ], \r\n  ...\r\n\r\n \r\n\r\n{\r\n   \"java_basics\": [\"Java Hello World - Tech Programmer\", \"Java Hello World using Eclipse IDE - Tech Programmer\",\r\n      \"Reading Java API documents - Tech Programmer\",\r\n       \"Common Java Exception and Error reference catalog - Tech Programmer\"],\r\n   \"jsp_servlets\": [\"First JSP\/Servlet Workshop - Tech Programmer\", \"Integrating Eclipse with Tomcat - Tech Programmer\",\r\n      \"Session Based Shopping Cart - Tech Programmer\"],\r\n    ...<\/code><\/pre>\n<pre class=\"code-style\">\u00a0<\/pre>\n<p><strong>Web page<\/strong><\/p>\n<p>We need to create a simple html page in which all the action takes place. By\u00a0action we mean,\u00a0selecting one dropdown causing another dropdown to be displayed and so on. List of things to be done in this page are given below:<\/p>\n<ol>\n<li>Add three html div elements. Two for each dropdowns and one for the article list.<\/li>\n<li>Are we using Javascript? No. Don&#8217;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.<\/li>\n<li>We need to write the jquery code for performing all the on change action.<\/li>\n<\/ol>\n<p>Let us go through each of the task in detail to finish off this workshop. Here we go&#8230;.<\/p>\n<p>1. Adding three html\u00a0DIV\u00a0elements<\/p>\n<pre class=\"language-markup\"><code>&lt;div style=\"position: absolute; top: 50px; left: 5px\"&gt;Section: &lt;select id=\"section\" name=\"section\"&gt;\r\n&lt;option value=\"select\"&gt;Select&lt;\/option&gt;\r\n&lt;option value=\"java_programming\"&gt;Java Programming&lt;\/option&gt;\r\n&lt;option value=\"market_analysis\"&gt;Market Analysis&lt;\/option&gt;\r\n&lt;\/select&gt;\r\n&lt;\/div&gt;\r\n\r\n&lt;div id=\"divCategory\" style=\"position: absolute; top: 80px; left: 5px; display:none\"&gt;\r\n  Category: &lt;select id=\"category\" name=\"category\"&gt;&lt;\/select&gt;\r\n&lt;\/div&gt;\r\n&lt;div id=\"divArticles\" style=\"position: absolute; top: 120px; left: 5px; display:none\"&gt;test\r\n&lt;\/div&gt;<\/code><\/pre>\n<p>Note the last two\u00a0DIV\u00a0elements are marked as hidden for starters by setting the style as &#8216;display:none&#8217;. Have you noticed the missing\u00a0<em>onChange<\/em>\u00a0on each of the select\/options element? Not sure, how all these are going to work!<\/p>\n<p>2. Adding link to Jquery library:<\/p>\n<pre class=\"language-markup\"><code>&lt;script type=\"text\/javascript\" src=\"static\/jquery-1.3.1.js\"&gt;&lt;\/script&gt;<\/code><\/pre>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>3. Writing Jquery code:<\/p>\n<p>Welcome to the fun side of\u00a0this workshop!<\/p>\n<p>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.<\/p>\n<pre class=\"language-markup\"><code>&lt;script type=\"text\/javascript\"&gt;\r\n   $(document).ready( function() {\r\n\r\n    });\r\n&lt;\/script&gt;<\/code><\/pre>\n<p>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!\u00a0<\/p>\n<p>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.<\/p>\n<pre class=\"language-javascript\"><code> $(\"#section\").change( function () {\r\n\r\n  }<\/code><\/pre>\n<p>The\u00a0pound (#)\u00a0symbol 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 $(\u00e2\u201a\u00ac\u00c5\u201c.class\u00e2\u201a\u00ac\u009d) and $(&#8216;div&#8217;). Refer to Jquery documentation (<a href=\"http:\/\/docs.jquery.com\/\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http:\/\/docs.jquery.com\/<\/a>) for more details.<\/p>\n<p>Getting back to our example, all the code for on selection of a section should go inside the above change function.<\/p>\n<p>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:<\/p>\n<pre class=\"language-javascript\"><code> $.getJSON(\"static\/site_category.json\",  function(json) {\r\n        var catJson = json[sSec];\/\/Fetch content for appropriate section\r\n        var options = \"&lt;option value=\\\"select\\\"&gt;Select&lt;\/option&gt;\";\/\/A variable which we build\r\n        for(i=0;i&lt;catJson.length;i++) {\/\/iterating contents for the selected section\r\n         \r\n          options +=\"&lt;option value=\\\"\"+catJson[i].ky+\"\\\"&gt;\"+catJson[i].val+\"&lt;\/option&gt;\";\/\/generate option for each category\r\n        }\r\n        $(\"#category\").html(options);\/\/inject options into select tag\r\n        $(\"#divCategory\").show();\/\/Magic! show the category div   \r\n       });\r\n      }<\/code><\/pre>\n<p align=\"justify\">$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\u00a0another article with these details.<\/p>\n<p align=\"justify\">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&#8217;ve had with it.<\/p>\n<p align=\"justify\">On selection of category, a list of articles\u00a0is displayed in the same way. The source is bundled into zip and can be downloaded by clicking here (<a title=\"Source code download\" href=\"https:\/\/www.tech-freaks.com\/wp-content\/uploads\/2009\/02\/jquery_json.zip\" rel=\"nofollow\">jquery_json.zip<\/a>).<\/p>\n<p align=\"justify\">You can check this stuff in action by accessing the link (<a title=\"Demo of Jquery with JSON\" href=\"sourcecode\/jquery_json\/jquery_json.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Code in action<\/a>).<\/p>\n<p align=\"justify\">This example is close to an AJAX based dropdown list. Once you understand this we would like to explain how we could use Jquery\u00a0 and JSON to access dynamic server side objects for generating subsequent dropdowns.<\/p>\n<p align=\"justify\">It is time for us to welcome Jquery, the Prince, who will be the next King to rule the client side world!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This workshop is for you, if: You would like to know how Jquery and JSON work together You are trying [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[7],"tags":[],"class_list":["post-79","post","type-post","status-publish","format-standard","hentry","category-javascript"],"_links":{"self":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/79","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/comments?post=79"}],"version-history":[{"count":0,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/79\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/media?parent=79"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/categories?post=79"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/tags?post=79"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}