<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Javascript &#8211; Tech-Freaks.com</title>
	<atom:link href="https://www.tech-freaks.com/java/javascript/feed" rel="self" type="application/rss+xml" />
	<link>https://www.tech-freaks.com</link>
	<description></description>
	<lastBuildDate>Mon, 30 Jun 2025 02:42:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.tech-freaks.com/wp-content/uploads/2025/07/cropped-tech-freaks-site-icon-512x512-1-32x32.png</url>
	<title>Javascript &#8211; Tech-Freaks.com</title>
	<link>https://www.tech-freaks.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Javascript with JSON</title>
		<link>https://www.tech-freaks.com/java/javascript/json-javascript.html</link>
					<comments>https://www.tech-freaks.com/java/javascript/json-javascript.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sun, 20 Jan 2013 05:10:11 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2013/01/20/json-javascript/</guid>

					<description><![CDATA[This workshop is for you, if: You are looking for a data structure to store your data for easy javascript [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="77"
					data-ulike-nonce="065985550b"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_77"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>This workshop is for you, if:</strong></p>
<ul style="text-align: left;">
<li>You are looking for a data structure to store your data for easy javascript access</li>
<li>You have seen JSON structure but do not know, how to access it using javascript</li>
</ul>
<p style="text-align: left;"><strong>This workshop is not for you, if:</strong></p>
<ul style="text-align: left;">
<li>You have no idea about client side scripting</li>
</ul>
<p style="text-align: left;">This workshop intends to provide hands on example on creating JSON structure and accessing the contents of the JSON using Javascript.</p>
<p style="text-align: left;"><strong>&#8216;JSON&#8217; the new kid in town</strong></p>
<p style="text-align: left;">JSON which stands for JavaScript Object Notation is the new buzz word and will definitely look good in your resume! But, how is JSON useful from a technology perspective.</p>
<ul style="text-align: left;">
<li>JSON can store data in the client side, where data security is not important.</li>
<li>JSON can be used for data exchange just like XML. But, why not XML itself? JSON comes handy when the exchanged data needs to be handled in the client side. JSON structure is easy to be manipulated in client side using javascript.</li>
</ul>
<p style="text-align: left;"><strong>Workshop Requirement</strong></p>
<p style="text-align: left;">Let us say, we need to maintain the summary of contents of this website. We want the data not to be maintained in database. We need to get information from a data structure using Javascript and of course, this data is not sensitive. The website contains, two sections (while writing this article), Java Programming and Stock Market. Each section contains categories and each category contains articles. Based on this data, we would like to see the number of pages in Java category etc.</p>
<p style="text-align: left;"><strong>Meeting JSON flesh and blood</strong></p>
<p style="text-align: left;">Enough talking about JSON! Let us actually see a JSON structure. The code snippet provided below shows a JSON structure assigned to a Javascript variable. When we use JSON for data exchange, we will write or receive JSON structure starting from braces without the javascript variable. To convert this into a javascript variable, we can use &#8216;eval&#8217; function, which is not recommended. There are parsers available in <a title="www.json.org" href="http://www.json.org/" target="_blank" rel="nofollow noopener noreferrer"><span style="text-decoration: underline;"><span style="color: #800080;">JSON.org</span></span></a> which converts the JSON structure to javascript variable.</p>
<pre class="language-javascript"><code>var varSiteData = {
  "sections" : [ //Array
     {//Each element in array, ie. Section is a structure not a simple attribute
      "name": "Java Programming", //this is a simple attribute
      "categories": [
      {
         "name":"Java Basics",
         "articles": [
         {
            "name" : "Java Hello World",
            "pages" : "1",
            "author" : "Tech Programmer"         
         },
         {
            "name" : "Java Hello World using Eclipse IDE",
            "pages" : "5",
            "author" : "Tech Programmer"         
         },
         ...
         ...
       ]
      },
      ...
      ...
     ]
    },
    ...
    ....
   ]
 }</code></pre>
<pre class="code-style" style="text-align: left;"></pre>
<p style="text-align: left;">Let us try to understand the syntax. JSON always start and end with curly braces. They contain attributes. The value of each attribute can be simple string, a structure (which internally is composed of many simple string attributes), array of simple string or array of structures. Here &#8220;section&#8221; is an attribute. How many sections we have in the site? Two, Java programming and Stock market. This calls for an array. Arrays are defined by square brackets. Now, each section contains categories. Also, each section needs a name to be stored. So, we have added an attribute by &#8220;name&#8221;. Attribute &#8220;name&#8221; is a simple string. Other attributes shown work in the same way. Click <a title="JSON in JS" href="sourcecode/JSON/v1/website_json.js" target="_blank" rel="nofollow noopener noreferrer">here</a> to download the complete JSON structure stored in JS file.</p>
<dl id="tf-message">
<dd class="message message fade">
<ul>
<li>An attribute name or key cannot start with numeric value. Although this is not a rule written anywhere, when the key or attribute name starts with or is a numeric value, the javascript which parse through the JSON does not understand the key. A simple workaround to resolve this issue is to append a constant string before the numeric value. Example: &#8220;str_25&#8221;</li>
</ul>
</dd>
</dl>
<p style="text-align: left;"> One more important thing is, if for an attribute, the value needs to be multiple attributes but not an array, then it is achieved using curly brackets only. A simple snippet which shows the attribute structure for Alphonsa mango:</p>
<pre class="language-javascript"><code>"alphonsa" : {
  "type": "mango",
  "taste": "sweet",
  "color": "yellow"
}</code></pre>
<p style="text-align: left;">Well, that&#8217;s that. We got started with JSON. But, let us try to have a quick look, why JSON is compared with XML. See the above JSON structure in an XML format.</p>
<pre class="language-markup"><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
&lt;sections&gt;
  &lt;section&gt;
     &lt;name&gt;Java Programming&lt;/name&gt;
     &lt;category&gt;
        &lt;name&gt;Java Basics&lt;/name&gt;
        &lt;article&gt;
           &lt;name&gt;Java Hello World&lt;/name&gt;
           &lt;pages&gt;1&lt;/pages&gt;
           &lt;author&gt;Tech Programmer&lt;/author&gt;
        &lt;/article&gt;
        &lt;article&gt;
           &lt;name&gt;Java Hello World using Eclipse IDE&lt;/name&gt;
           &lt;pages&gt;5&lt;/pages&gt;
           &lt;author&gt;Tech Programmer&lt;/author&gt;
        &lt;/article&gt;
       ...
       ...
     &lt;/category&gt;
  &lt;/section&gt;
..
&lt;/sections&gt;</code></pre>
<p style="text-align: left;"><strong>Validating JSON structure</strong></p>
<p style="text-align: left;">Just like we validate XML structures using Internet Explorer and other tools for well-formedness, there are certain JSON viewers available, which verify the JSON structure and provide details regarding any missing braces etc. <a title="JSON Viewer" href="http://www.codeplex.com/JsonViewer" target="_blank" rel="nofollow noopener noreferrer"><span style="text-decoration: underline;"><span style="color: #800080;">JSON Viewer</span></span></a> is one such hand helpful too.</p>
<p style="text-align: left;"><strong>Javascript and JSON</strong></p>
<p style="text-align: left;">Now, let us see how Javascript can access different elements within the JSON structure. We will try to calculate the total number of pages in &#8216;Stock Market&#8217; and &#8216;Java Programming&#8217; section. The HTML page includes the JSON data from a JS file. The javascript present in the HTML page iterates through the JSON structure to determine the result.</p>
<p style="text-align: left;">See the below javascript function, with comments explaining how the JSON structure is iterated through.</p>
<pre class="language-javascript"><code>function getSectionTotalPages(section) {

 //entry point into JSON variable..Accessing sections attribue, which is an array
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 //loop through each of the sections
 for(var i=0;i&lt;arrSections.length;i++) {
  var currSection = arrSections[i];
  //we get the section for which we want to calculate the page total
  if(currSection.name==section) {
   //Now into category array from section
   var arrCategories = currSection.categories;
   
   //loop through the category array
   for(var j=0;j&lt;arrCategories.length;j++) {
    var currCategory = arrCategories[j];
    //For each category, get the article list (array)
    var arrArticles = currCategory.articles;
    //loop through each article
    for(var k=0;k&lt;arrArticles.length;k++) {
     var currArticle = arrArticles[k];
 
     //for each article, get the # of pages and add it to total
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   //This method works for one section, so break the loop, if the section is found
   break;
  }
 }
 return totalPages;
}</code></pre>
<pre class="brush:javascript" style="text-align: left;"><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">The complete HTML containing the javascripts is given below. On clicking the compare button, the compareSectionPages function is called. It internally,calls getSectionTotalPages function twice, for getting pages for </span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">Java Programming</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;"> section and </span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">Market Analysis</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;">'</span><span style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;"> section.</span></pre>
<pre class="language-markup"><code>&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;JSON and Javascript example&lt;/title&gt;
  &lt;script type="text/javascript" src="website_json.js" &gt;&lt;/script&gt;
  &lt;script language="javascript" type="text/javascript"&gt;
  function getSectionTotalPages(section) {
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 for(var i=0;i&lt;arrSections.length;i++) {
  var currSection = arrSections[i];
  if(currSection.name==section) {
   var arrCategories = currSection.categories;
  for(var j=0;j&lt;arrCategories.length;j++) {

    var currCategory = arrCategories[j];
    var arrArticles = currCategory.articles;
    for(var k=0;k&lt;arrArticles.length;k++) {
     var currArticle = arrArticles[k];
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   break;
  }
 }
 return totalPages;
}

  function compareSectionPages() {
   var totalJavaPages = getSectionTotalPages('Java Programming');
 var totalMarketPages = getSectionTotalPages('Market Analysis');
   var result = "&lt;table border='1'&gt;&lt;tr&gt;&lt;td&gt;Java Programming&lt;/td&gt;&lt;td&gt;Market Analysis&lt;/td&gt;

&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;"+totalJavaPages+"&lt;/td&gt;&lt;td&gt;"+totalMarketPages+"&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";
   document.getElementById('result').innerHTML = result;
  }

  &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h2&gt;Welcome to JSON with javascript workshop!&lt;/h2&gt;
  &lt;p&gt;
  &lt;input type="button" name="button1" value="Compare Section pages" onclick="compareSectionPages();"&gt;

  &lt;p&gt;&lt;p&gt;
  Result: &lt;div id="result"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p style="text-align: left;"> And the result is 17 to 12. Java programming wins by 5 goals!</p>
<p style="text-align: left;">The author of the &#8216;Market analysis&#8217; section may feel bit hard done by.  Some articles missed out were missed out. &#8216;Technical Analysis&#8217; and &#8216;Market Summary&#8217; articles were not considered. We added every article inside the category, but these two articles are not maintained at category level. They are maintained in section level.</p>
<hr class="system-pagebreak" title="JSON flexibility" />
<p style="text-align: left;">Well, change is inevitable in the JSON structure! However, the flexibility of JSON will cover up for it. But, the change in data structure will cause a change to javascript code to calculate the total pages in section.</p>
<p style="text-align: left;">Let us get this thing fixed. For the JSON fix, a little thought will make it clear that adding articles inside section structure will be similar to articles maintained inside categories. The below code snippet shows the portion of the changed JSON:</p>
<pre class="code-style" style="text-align: left;"></pre>
<pre class="language-javascript"><code> ...
      {
      "name":"Market Analysis",
      "articles": [
       {
          "name": "Market Summary",
          "pages": "1",
          "author" : "Market Analyst"        
       },
       {
          "name": "Tech Analysis",
          "pages": "1",
          "author" : "Market Analyst"        
       }
      ] 
      ....
     .....</code></pre>
<p style="text-align: left;">The change in  getSectionTotalPages will be bit more challenging. Now, in the code we have to deal with one section, which has articles array and another which does not. Also, this method needs to be generic enough to handle any new sections added to the website in the future. Some of the section may have articles inside it and some may not. Many times, while using javascript we see the &#8216;undefined&#8217; variable. We will have to use this, to check if articles array is present directly within sections.</p>
<p>The below modified function getSectionTotalPages will do the trick. See the comments explaining the main changes and the <em>typeof</em> function used to good effect.</p>
<pre class="language-javascript"><code>function getSectionTotalPages(section) {
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 for(var i=0;i&lt;arrSections.length;i++) {
  var currSection = arrSections[i];
  if(currSection.name==section) {
   //Check if articles inside section is undefined (does not exist)
   //If not undefined, then section as articles like Market Analysis section
   if(typeof(currSection.articles)!='undefined') {

    var arrSecArticles = currSection.articles;
    for(var j=0;j&lt;arrSecArticles.length;j++) {
     var currSecArticle = arrSecArticles[j];
     totalPages = totalPages + parseInt(currSecArticle.pages);

    }
   }
   var arrCategories = currSection.categories;

   for(var j=0;j&lt;arrCategories.length;j++) {
    var currCategory = arrCategories[j];
    var arrArticles = currCategory.articles;
    for(var k=0;k&lt;arrArticles.length;k++) {
     var currArticle = arrArticles[k];
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   break;
  }
 }
 return totalPages;
}</code></pre>
<p style="text-align: left;">Update the HTML code contents with the above updated function. Click <span style="text-decoration: underline;"><span style="color: #0066cc;"><a title="JSON structure" href="sourcecode/JSON/v2/website_json.js" target="_blank" rel="nofollow noopener noreferrer">here</a></span></span> to download the updated JSON code. Place the HTML and JS file in the same directory. Access the HTML page from browser and then click the &#8216;Compare Section pages&#8217; button to view the result table. &#8216;Java Programming&#8217; still wins by a margin of 3!</p>
<p style="text-align: left;">Welcome to the whole new world of client side scripting with JSON!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/javascript/json-javascript.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using Jquery with JSONP</title>
		<link>https://www.tech-freaks.com/java/javascript/jquery-jsonp.html</link>
					<comments>https://www.tech-freaks.com/java/javascript/jquery-jsonp.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Sun, 21 Jun 2009 21:48:29 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2009/06/21/jquery-jsonp/</guid>

					<description><![CDATA[The workshop is for This workshop is dedicated to all those who are stuck with cross-domain communication issue trying to [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="81"
					data-ulike-nonce="f7abfe586c"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_81"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p style="text-align: left;"><strong>The workshop is for</strong></p>
<p style="text-align: left;">This workshop is dedicated to all those who are stuck with cross-domain communication issue trying to fetch JSON data from a different domain using Jquery.</p>
<p><strong>Introduction</strong></p>
<p style="text-align: left;">This workshop is built up based on &#8216;JSON with Jquery&#8217; workshop. It starts by providing a working example of JSON service accessed by Jquery and highlights cross-domain communication issue while trying to access JSON data from a different domain. It then goes on showing the resolution using JSONP (JSON with Padding).</p>
<p><strong>Quick Recap</strong></p>
<p style="text-align: left;">Let us have a quick recap of the example &#8216;JSON with Jquery&#8217;. However, it is strongly recommended to have go through <a title="Using Jquery with JSON" href="Java-Programming/Javascripts/jquery-json.html" target="_blank" rel="noopener noreferrer">JSON with Jquery </a>workshop just to get an idea of what the example deals with. Here is a summary:</p>
<ol style="text-align: left;">
<li>A HTML page has the Jquery code to access JSON and generate dynamic dropdowns.</li>
<li>There are two predefined static JSON files one for category and another for articles.</li>
</ol>
<p style="text-align: left;"><strong>Dynamically generated JSON files</strong></p>
<p>We will be modifying the previous workshop example to generate dynamic JSON files using server side components (like JSP/Servlet, PHP etc). So, we will create a JSP/PHP which spits out a JSON data. We create a PHP file by the name getSiteJSON.php. Here, we merge the content of two static JSON files used previously into a single server component. Note that our JSON file is still static, as the contents are hardcoded. However, in real life your JSON contents will be dynamically pulled from the database.</p>
<p>The below code snippet highlights the change in the Jquery JSON call in the html file.</p>
<pre class="language-javascript"><code>$.getJSON("http://www.stage3.tech-freaks.in/sourcecode/jquery_jsonp/
                      getSiteJson.php?type=category",  function(json) {
          var catJson = json[sSec];
          var options = "&lt;option value=\"select\"&gt;Select&lt;/option&gt;";
          for(i=0;i&lt;catJson.length;i++) {</code></pre>
<p>The below code snippets is a PHP code which generates JSON.</p>
<pre class="language-php"><code>   $type = $_GET['type'];
    $jsonData = "";
    if($type=="category")
        $jsonData = "{\"java_programming\": [ { \"ky\": \"java_basics\", ....}]}";
    else
        $jsonData = "{\"java_basics\": [\"Java Hello World - Tech Programmer\", ...]}";
    echo $jsonData;</code></pre>
<p style="text-align: left;"> You may want to check the working of the getSiteJSON.php by accessing the page directly with query parameter of &#8216;type=category&#8217; or &#8216;type=article&#8217; and see the JSON printed in the page.</p>
<p><strong>Cross domain JSON fetch</strong></p>
<p style="text-align: left;">Now, let us assume that we want to get the site data as JSON from a different site. From a technical perspective, this means that getSiteJSON.php or some service similar to it is present in a different domain. This is common with JSON services provided by a different site and used by another site. </p>
<p>For this workshop, we simulate this scenario by hosting the getSiteJSON.php in <em>www.stage3.tech-freaks.in</em> and the HTML page which fetches the JSON content using Jquery in <em>www.tech-freaks.in</em>.</p>
<p>Uploading files&#8230;..</p>
<p>Check <a title="Cross domain JSON issue" href="sourcecode/jquery_jsonp/jquery_json.html" target="_blank" rel="nofollow noopener noreferrer">JSON service from cross-domain</a> by checking this demo.</p>
<p>Oops! The drop-downs are not loading. Let check the error console in FireFox (from menu Tools &gt;&gt; Error Console).</p>
<p>We see two error lines as below:</p>
<dl id="tf-message">
<dd>
<p style="text-align: left;"><code>Error: [Exception... "Access to restricted URI denied"  code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"  location: "... Line: ..."]</code><br /><code>Source File: ....</code><br /><code>Line: ...</code></p>
<p><code>Security Error: Content at file:... may not load data from .....</code></p>
</dd>
</dl>
<p style="text-align: left;">Hmmm, this is a cross domain JSON data fetch issue. So, when you try to access a JSON data using Jquery/AJAX call from a different domain, we see the browser slapping the above error message on our face.</p>
<p>Where do we go from here?</p>
<p><strong>JSONP comes to the party</strong></p>
<p style="text-align: left;">JSONP stands for JSON with Padding. It is a work around used to resolve the cross domain dynamic JSON fetch problems by wrapping the JSON data in a function. So, what we return is something like:</p>
<pre class="language-javascript"><code>functionName({"java_programming": [ { "ky": "java_basics", "val": "Java Basics" }, ...]})</code></pre>
<p style="text-align: left;">The function name is passed as a parameter. In Jquery, during the getJSON call we pass a parameter &#8216;callback=?&#8217;. Jquery support JSONP and automatically generations a function name. The callback is the parameter in which the function name is passed.</p>
<p>Let us get to work. We want to modify the code for implementing JSONP.</p>
<ul>
<li style="text-align: left;"><em>jquery_json.html</em> : Rename this file to <em>jquery_jsonp.html</em>for convention purpose. We will modify the jquery call in this HTML file to implement JSONP. The below code snippet highlights this call. </li>
</ul>
<pre class="language-javascript"><code>$.getJSON("http://www.stage3.tech-freaks.in/sourcecode/jquery_jsonp
  /getSiteJsonp.php?type=category&amp;callback=?", function(json) {
 var catJson = json[sSec];
 var options = "&lt;option value=\"select\"&gt;Select&lt;/option&gt;";</code></pre>
<ul>
<li style="text-align: left;"><em>getSiteJSON.php: </em>Rename this file to <em>getSiteJSONP.php</em> to provide an informative file name. We modify the code to return a padded JSON instead of simple JSON. The below snippet explains how the &#8216;callback&#8217; parameter is used to pad the JSON data with function name.</li>
</ul>
<pre class="language-php"><code> //echo $jsonData;
 echo $_GET['callback']."(".$jsonData.")";</code></pre>
<p>See <a title="JSONP Demo" href="sourcecode/jquery_jsonp/jquery_jsonp.html" target="_blank" rel="nofollow noopener noreferrer">JSONP in action</a>. See how the dropdowns get generated dynamically by fetching data from <em>www.stage3.tech-freaks.in</em>.</p>
<p>Download the complete <a title="JSONP and Jquery sourcecode" href="https://www.tech-freaks.com/wp-content/uploads/2009/06/jsonp_src.zip" target="_blank" rel="nofollow noopener noreferrer">PHP source for JSONP </a>implementation <em>(<span style="color: #0000ff;">JSP Sourcecode for JSONP Implementation coming soon!</span>)</em>.</p>
<p>You no longer have to implement all services in house inside your domain. You can use JSONP to fetch JSON data using services implemented outside your domain.</p>
<p>Phew! The struggle finally ended. You deserve to put your feet up for sometime and enjoy a cup of coffee!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/javascript/jquery-jsonp.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using Jquery with JSON</title>
		<link>https://www.tech-freaks.com/java/javascript/jquery-json.html</link>
					<comments>https://www.tech-freaks.com/java/javascript/jquery-json.html#respond</comments>
		
		<dc:creator><![CDATA[Tech Programmer]]></dc:creator>
		<pubDate>Mon, 23 Feb 2009 02:52:32 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://localhost/tfcom_wp/2009/02/23/jquery-json/</guid>

					<description><![CDATA[This workshop is for you, if: You would like to know how Jquery and JSON work together You are trying [&#8230;]]]></description>
										<content:encoded><![CDATA[		<div class="wpulike wpulike-default " ><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button"
					aria-label="Like Button"
					data-ulike-id="79"
					data-ulike-nonce="20de8b6c75"
					data-ulike-type="post"
					data-ulike-template="wpulike-default"
					data-ulike-display-likers=""
					data-ulike-likers-style="popover"
					class="wp_ulike_btn wp_ulike_put_image wp_post_btn_79"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0"></span>			</div></div>
	<p>This workshop is for you, if:</p>
<ul>
<li>You would like to know how Jquery and JSON work together</li>
<li>You are trying to create series of dependent dropdowns based on data present in client side</li>
</ul>
<p><strong>Quick Introduction</strong><br />A brief introduction of the two technologies used in this workshop are given below.</p>
<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 <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>
<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 <a title="JSON with Javascript" href="Java-Programming/Javascripts/json-javascript.html" target="_blank" rel="noopener noreferrer">JSON</a> for more details.</p>
<p><strong>Requirements</strong></p>
<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>
<p><strong>Solution</strong></p>
<p>We identify and describe each element necessary for implementing the above mentioned requirement.</p>
<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>
<p>We maintain two different json files.</p>
<ul>
<li>site_category.json &#8211;  Maintains data related to sections and categories</li>
<li>site_articles.json &#8211;  Maintains the data related to categories and articles</li>
</ul>
<p> </p>
<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>
<pre class="language-javascript"><code>{
  "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 &amp; 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"],
    ...</code></pre>
<pre class="code-style"> </pre>
<p><strong>Web page</strong></p>
<p>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:</p>
<ol>
<li>Add three html div elements. Two for each dropdowns and one for the article list.</li>
<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>
<li>We need to write the jquery code for performing all the on change action.</li>
</ol>
<p>Let us go through each of the task in detail to finish off this workshop. Here we go&#8230;.</p>
<p>1. Adding three html DIV elements</p>
<pre class="language-markup"><code>&lt;div style="position: absolute; top: 50px; left: 5px"&gt;Section: &lt;select id="section" name="section"&gt;
&lt;option value="select"&gt;Select&lt;/option&gt;
&lt;option value="java_programming"&gt;Java Programming&lt;/option&gt;
&lt;option value="market_analysis"&gt;Market Analysis&lt;/option&gt;
&lt;/select&gt;
&lt;/div&gt;

&lt;div id="divCategory" style="position: absolute; top: 80px; left: 5px; display:none"&gt;
  Category: &lt;select id="category" name="category"&gt;&lt;/select&gt;
&lt;/div&gt;
&lt;div id="divArticles" style="position: absolute; top: 120px; left: 5px; display:none"&gt;test
&lt;/div&gt;</code></pre>
<p>Note the last two DIV elements are marked as hidden for starters by setting the style as &#8216;display:none&#8217;. Have you noticed the missing <em>onChange</em> on each of the select/options element? Not sure, how all these are going to work!</p>
<p>2. Adding link to Jquery library:</p>
<pre class="language-markup"><code>&lt;script type="text/javascript" src="static/jquery-1.3.1.js"&gt;&lt;/script&gt;</code></pre>
<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>
<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>
<p>3. Writing Jquery code:</p>
<p>Welcome to the fun side of this workshop!</p>
<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>
<pre class="language-markup"><code>&lt;script type="text/javascript"&gt;
   $(document).ready( function() {

    });
&lt;/script&gt;</code></pre>
<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! </p>
<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>
<pre class="language-javascript"><code> $("#section").change( function () {

  }</code></pre>
<p>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 $(&#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>
<p>Getting back to our example, all the code for on selection of a section should go inside the above change function.</p>
<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>
<pre class="language-javascript"><code> $.getJSON("static/site_category.json",  function(json) {
        var catJson = json[sSec];//Fetch content for appropriate section
        var options = "&lt;option value=\"select\"&gt;Select&lt;/option&gt;";//A variable which we build
        for(i=0;i&lt;catJson.length;i++) {//iterating contents for the selected section
         
          options +="&lt;option value=\""+catJson[i].ky+"\"&gt;"+catJson[i].val+"&lt;/option&gt;";//generate option for each category
        }
        $("#category").html(options);//inject options into select tag
        $("#divCategory").show();//Magic! show the category div   
       });
      }</code></pre>
<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 another article with these details.</p>
<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>
<p align="justify">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 (<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>
<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>
<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  and JSON to access dynamic server side objects for generating subsequent dropdowns.</p>
<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>
]]></content:encoded>
					
					<wfw:commentRss>https://www.tech-freaks.com/java/javascript/jquery-json.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
