<?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>JavaBeat &#187; AJAX</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Mon, 13 May 2013 20:10:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Using JSON forms with AJAX in Lift Framework</title>
		<link>http://www.javabeat.net/2011/05/using-json-forms-with-ajax-in-lift-framework/</link>
		<comments>http://www.javabeat.net/2011/05/using-json-forms-with-ajax-in-lift-framework/#comments</comments>
		<pubDate>Sat, 07 May 2011 00:28:58 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lift Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=723</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on Lift in Action, to be published on July 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>This article is based on <a href="http://www.manning.com/perrett/" target="_blank">Lift in Action</a>, to be published on July 2011. It is being reproduced here by permission from <a href="http://www.manning.com/" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.</p>
<p><center>Using JSON forms with AJAX</center></p>
<h2>Introduction</h2>
<p><strong>Lift</strong> has several different ways of interacting with forms and <strong>AJAX</strong>, and you can quite easily configure <strong>Lift</strong> to create an <strong>AJAX</strong> form using <strong>SHtml</strong>. <strong>SHtml</strong> contains many useful methods and should be your main port of call for all of the out-of-the-box <strong>AJAX</strong> functionality. One of the other interesting facilities that this object provides is the ability to create forms that are serialized and sent to the server using <strong>JSON</strong>. Listing 1 details an example of using a <strong>JSON</strong> form.</p>
<p><strong><span style="color: red;">Listing 1 Implementing JSON Form</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">import scala.xml.NodeSeq
	import net.liftweb.util.JsonCmd
	import net.liftweb.util.Helpers._
	import net.liftweb.http.{SHtml,JsonHandler}
	import net.liftweb.http.js.{JsCmd}
	import net.liftweb.http.js.JsCmds.{SetHtml,Script}
	class JsonForm {
		def head = Script(json.jsCmd) 							#1
		def show = {
			&quot;#form&quot; #&gt;((ns: NodeSeq) =&gt; SHtml.jsonForm(json, ns)) 			#2
		}
		object json extends JsonHandler { 						#3
			def apply(in: Any): JsCmd =
			SetHtml(&quot;json_result&quot;, in match {
				case JsonCmd(&quot;processForm&quot;, _, params: Map[String, Any], _) =&gt; 	#4
				&lt;p&gt;Publisher: {params(&quot;publisher&quot;)}, 				#4
					Title: {params(&quot;title&quot;)}&lt;/p&gt;				#4
				case x =&gt;
					&lt;span class=&quot;error&quot;&gt;Unknown issue handling JSON: {x}&lt;/span&gt;
			})
		}
	}
	#1 Registers JSON serialize function
	#2 JSON form wrapper
	#3 Custom JSON handler
	#4 Parameter handling</pre></td></tr></table></div>

<p>Here, you can see that this is a basic class with a few snippet methods. #1 details a snippet that simply adds a JavaScript element to the page. Typically, you would call this method from the &lt;head&gt; tag within your template so that the head is merged into the main page template. The point of this is that the JsonHandler implementation— in this instance the <strong>JSON</strong> object—contains JavaScript that registers a function to serialize the passed object to <strong>JSON</strong>. #2 is a snippet method setup that simply binds to the jsonForm method passing the JsonHandler instance and the passed NodeSeq. This generates a &lt;form&gt; element that will wrap the fields in your template. A point of note here is that the fields in your template won&#8217;t have randomized names because they are not generated with <strong>SHtml</strong> helpers. They are &#8220;raw&#8221; from the template so, from a security perspective, this is important to keep in mind.</p>
<p>Listing 2 shows the full contents of the template. Section #3 is the implementation of the JsonHanlder, but specifically the point of interest is #4. This defines the handling of parameters passed from the browser. As params is a Map, you must be careful to request only the keys that actually exist because this could throw a runtime exception if the key you are expecting does not exist.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><strong><span style="color: red;">Listing 2 Template implementation for JSON form</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;div class=&quot;lift:surround?with=default;at=content&quot;&gt;
		&lt;head&gt;
			&lt;script type=&quot;text/javascript&quot; src=&quot;/classpath/jlift.js&quot; /&gt; 		#1
			&lt;lift:json_form.head /&gt; 						#1
		&lt;/head&gt;
		&lt;h2&gt;JSON Form&lt;/h2&gt;
		&lt;div id=&quot;form&quot; class=&quot;lift:JsonForm.show&quot;&gt; 					#2
			&lt;p&gt;Book Name: &lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;title&quot; /&gt;&lt;/p&gt; 		#3
			&lt;p&gt;Publisher: &lt;br /&gt;
				&lt;select name=&quot;publisher&quot;&gt; 					#3
					&lt;option value=&quot;manning&quot;&gt;Manning&gt;/option&gt; 		#3
					&lt;option value=&quot;penguin&quot;&gt;Penguin&lt;/option&gt; 		#3
					&lt;option value=&quot;bbc&quot;&gt;BBC&lt;/option&gt; 			#3
				&lt;/select&gt; 							#3
			&lt;/p&gt;
			&lt;p&gt;&lt;input type=&quot;submit&quot; /&gt;&lt;/p&gt; 						#3
		&lt;/div&gt;
		&lt;hr /&gt;
		&lt;h2&gt;JSON Result&lt;/h2&gt;
		&lt;div id=&quot;json_result&quot;&gt;&gt;/div&gt; 							#4
	&lt;/div&gt;
&nbsp;
	#1 Includes jlift.js
	#2 Calls snippet method
	#3 Input fields
	#4 Result element</pre></td></tr></table></div>

<p><strong>Lift</strong> actually provides a specialized client-side JavaScript library with a set of helper functions for conducting operations such as serializing forms, handling collections, and so forth, called jlift.js. Here it is included at #1, which is important; otherwise, the <strong>AJAX</strong> functionality would not operate as expected. When the library is included and the head method in the JsonForm class is called from the template, you will be left with something similar to the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">	&lt;script src=&quot;/classpath/jlift.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	&lt;script type=&quot;text/javascript&quot;&gt;
	//&lt;![CDATA[
		function F950163993256RNF(obj){
			liftAjax.lift_ajaxHandler('F950163993256RNF='+
			encodeURIComponent(JSON.stringify(obj)), null,null);
		}
	//]]&gt;
	&lt;/script&gt;</pre></td></tr></table></div>

<p>You need to call the head method from your template so the rendered output includes this function.</p>
<h2>Summary</h2>
<p>We covered how you can leverage the <strong>SHtml</strong> <strong>AJAX</strong> builder methods to create page elements that trigger server-side actions. The powerful thing about <strong>Lift</strong>&#8216;s <strong>AJAX</strong> system is that you can capture the logic to be executed upon making the specific callback within a Scala function.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fweb-frameworks%2Fajax%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/web-frameworks/ajax/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/web-frameworks/ajax/feed/" data-count="vertical" data-text="AJAX" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/05/using-json-forms-with-ajax-in-lift-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Asynchronous File Upload using Ajax, jQuery Progress Bar and Java</title>
		<link>http://www.javabeat.net/2011/03/asynchronous-file-upload-using-ajax-jquery-progress-bar-and-java/</link>
		<comments>http://www.javabeat.net/2011/03/asynchronous-file-upload-using-ajax-jquery-progress-bar-and-java/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 13:33:44 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=582</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction Download jQuery File Upload Sample Code Source Code for jQuery File Upload In this tutorial you will learn about Asynchronous File Upload using Ajax, jQuery Progress Bar and Java The image below shows a screenshot of the file upload that we are going to learn in this tutorial. Let us see what all is [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<h2>Download jQuery File Upload Sample Code</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/sourcecode/2011/201103-file-upload-jquery.zip">Source Code for jQuery File Upload</a></li>
</ul>
<p>In this tutorial you will learn about <strong><em>Asynchronous File Upload using Ajax, jQuery Progress Bar and Java</em></strong></p>
<p>The image below shows a screenshot of the file upload that we are going to learn in this tutorial.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/15.jpg"><img class="aligncenter size-medium wp-image-1090" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/03/15-300x67.jpg" alt="" width="300" height="67" /></a>Let us see what all is needed to develop this application. We shall create a web application which has the following files.</p>
<ul>
<li>FileUpload.html (The html/jsp file where the file upload happens)</li>
<li>jQuery related script files(We are going to discuss about this in detail later)</li>
<li>FileUploadListener.java(The listener file which listens to the file upload)</li>
<li>FileUploadListener.java (The servlet file which takes care of the upload process)</li>
<li>web.xml</li>
</ul>
<p>The image below shows the screenshot of the file Structure. We have used netBeans IDE to develop the web Application.</p>
<h2>File Structure</h2>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/25.jpg"><img class="aligncenter size-medium wp-image-1089" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/03/25-161x300.jpg" alt="" width="161" height="300" /></a>Let us try to understand the webstructure.We have a <strong><em>web</em></strong> folder which has FileUpload.html.The <strong><em>source packages</em></strong> has a java package &#8220;fileupload&#8221; which has two java files <strong>FileUploadListener.java</strong> and <strong><em>FileUploadServlet.java</em></strong></p>
<p>There is another folder called &#8220;<strong><em>scripts</em></strong>&#8221; which has jquery.js which is used for the core javascript and Ajax features of jQuery library.<br />
Apart from this we also have <strong><em>ui.core.js</em></strong> and <strong><em>ui.progressbar.js</em></strong>. These files are necessary for constructing a progress bar using jQuery.You can download the latest version of jQuery from <a href="http://docs.jquery.com/Downloading_jQuery" target="_blank">Download jQuery</a></p>
<p>The jquery progress bar can be downloaded from <a href="http://jqueryui.com/download" target="blank">Download jQuery UI</a></p>
<p>Now let us add in code into <strong><em>FileUpload.html</em></strong><br />
We shall be adding script , style and html body sections to the html files. Lets deal with each one of these sections one after the other.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Please find below the code for the html body section.</p>
<h2>Html Body Code</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;body&gt;
		&lt;center&gt;
			&lt;h2 class=&quot;backgroundClass&quot;&gt;Sample File Upload&lt;/h2&gt;
			&lt;form id=&quot;myForm&quot; enctype=&quot;multipart/form-data&quot; method=&quot;post&quot; target=&quot;uploadFrame&quot; 
				action=&quot;example/FileUploadServlet&quot; onsubmit=&quot;ajaxFunction()&quot;&gt;
				&lt;table border=&quot;1&quot;&gt;
					&lt;tr&gt;&lt;td&gt; &lt;h4&gt;File to be uploaded &lt;/h4&gt;&lt;/td&gt;&lt;td&gt;  &lt;input type=&quot;file&quot; name=&quot;txtFile&quot; id=&quot;txtFile&quot;		/&gt;&lt;/td&gt;&lt;/tr&gt;
					&lt;tr&gt;&lt;td align=&quot;center&quot; colspan=&quot;2&quot;&gt;  &lt;input type=&quot;submit&quot; id=&quot;submitID&quot; name=&quot;submit&quot; value=&quot;Upload&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;/table&gt;
			&lt;/form&gt;
			&lt;div id=&quot;progressbarWrapper&quot; style=&quot;height:20px;width:100px; &quot;&gt;
				&lt;div id=&quot;progressbar&quot; style=&quot;height:100%;&quot;&gt;&lt;/div&gt;
			&lt;/div&gt;
			&lt;br/&gt;
			&lt;div id=&quot;status&quot; style=&quot;display:none&quot;&gt;
				&lt;table width=&quot;100%&quot; class=&quot;backgroundClass&quot;&gt;
					&lt;tr&gt;
					&lt;td align=&quot;center&quot; nowrap=&quot;nowrap&quot;&gt;
						&lt;div id=&quot;percentDone&quot; style=&quot;font-weight: bold;&quot;&gt; &lt;/span&gt;
					&lt;/td&gt;
					&lt;/tr&gt;
				&lt;/table&gt;	
				&lt;table width=&quot;100%&quot; class=&quot;backgroundClass&quot;&gt;
					&lt;tr&gt;
					&lt;td align=&quot;center&quot; nowrap=&quot;nowrap&quot;&gt;
						&lt;div id=&quot;bytesRead&quot; style=&quot;font-weight: bold;&quot;&gt; &lt;/span&gt;
					&lt;/td&gt;
					&lt;/tr&gt;
				&lt;/table&gt;	
				&lt;table width=&quot;100%&quot; class=&quot;backgroundClass&quot;&gt;
					&lt;tr&gt;
					&lt;td align=&quot;center&quot; nowrap=&quot;nowrap&quot;&gt;
						&lt;div id=&quot;totalNoOfBytes&quot; style=&quot;font-weight: bold;&quot;&gt; &lt;/span&gt;
					&lt;/td&gt;
					&lt;/tr&gt;
				&lt;/table&gt;
			&lt;/div&gt;
		&lt;/center&gt;
		&lt;/body&gt;</pre></td></tr></table></div>

<h2>Script Code</h2>
<p>Add the following code to the script section.<br />
The script code pasted below will import the various script files necessary for jQuery core functions, progress bar and Ajax.<br />
After importing, we need to do the following tasks:</p>
<ul>
<li>Add the progressbar to the page(The progress bar will be hidden on the load of the page and will be shown only when the file upload begins.)</li>
<li>Make an Ajax request to the java Servlet(Servlet code will be discussed later).The Java Servlet will take care of the file upload on the server.</li>
<li>The <strong><em>ajaxFunction()</em></strong> will take care of sending the xmlHttpRequest.</li>
<li><strong><em>funcReadyStateChange()</em></strong> will be invoked soon after getting the output.It takes care of the collecting the servlet output which is in the form of XML.<strong><em>funcReadyStateChange()</em></strong>will also take care of:
<ul>
<li>Parsing the response XML.</li>
<li>Updating the progress bar value through <strong><em>updateProgressbar()</em></strong> function</li>
<li>Update the page with the response.</li>
</ul>
</li>
<li>The output xml will have details about the total number of bytes present in the file and the number of bytes uploaded.</li>
<li>Please note that the funcReadyState will make repetitive calls to ajaxFunction() and updateProgressBar() until the file is completely uploaded.Every request that is sent will get the recent most values of the &#8220;number of bytes that are uploaded&#8221; from the server.</li>
</ul>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;script src=&quot;scripts/jquery.js&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;scripts/ui.core.js&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;scripts/ui.progressbar.js&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;scripts/ui.resizable.js&quot;&gt;&lt;/script&gt;
	&lt;script&gt;
		var progressBarValue=0;
		$(document).ready(function() {
			$( &quot;#progressbar&quot; ).progressbar({             value:0         });
			document.getElementById(&quot;progressbarWrapper&quot;).style.display = &quot;none&quot;;
		});
        function updateProgressBar(progressBarValue)
        {
			$(&quot;#progressbar&quot;).progressbar(&quot;option&quot;,&quot;value&quot;,progressBarValue);
		}
        var req;
&nbsp;
        function ajaxFunction(){
			var url = &quot;example/FileUploadServlet&quot;;
&nbsp;
            if (window.XMLHttpRequest){ 
				req = new XMLHttpRequest();
                try{
					req.onreadystatechange = funcReadyStateChange;
                    req.open(&quot;GET&quot;, url, true);
                } catch (e) {
					alert(e);
                }
                req.send(null);
            }
&nbsp;
            else if (window.ActiveXObject) { 
				req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
                if (req) {
					req.onreadystatechange = funcReadyStateChange;
                    req.open(&quot;GET&quot;, url, true);
                    req.send();
                }
            }
        }
&nbsp;
        function funcReadyStateChange(){
			if (req.readyState == 4){
				if (req.status == 200){
					var xml = req.responseXML;
					var responseNode=xml.getElementsByTagName(&quot;response&quot;)[0];
					var noOfBytesRead =responseNode.getElementsByTagName(&quot;bytes_read&quot;)[0].
						childNodes[0].nodeValue;
					var totalNoOfBytes = responseNode.getElementsByTagName(&quot;content_length&quot;)[0].
						childNodes[0].nodeValue;
					progressBarValue=noOfBytesRead/totalNoOfBytes*100;             
					document.getElementById(&quot;status&quot;).style.display=&quot;block&quot;;
					document.getElementById(&quot;percentDone&quot;).innerHTML=&quot;Percentage Completed: &quot;
						+Math.floor(progressBarValue)+&quot;%&quot;;
					document.getElementById(&quot;bytesRead&quot;).innerHTML= &quot;Number Of Bytes Read: &quot;+
						noOfBytesRead;
					document.getElementById(&quot;totalNoOfBytes&quot;).innerHTML= &quot;Total Number Of Bytes: &quot;+
						totalNoOfBytes;
					document.getElementById(&quot;progressbarWrapper&quot;).style.display = &quot;block&quot;;
&nbsp;
                    if (progressBarValue&lt;100){
						window.setTimeout(&quot;ajaxFunction();&quot;, 100);
                        window.setTimeout(&quot;updateProgressBar(progressBarValue);&quot;, 100);
&nbsp;
                    } else {
                        alert(&quot;Done&quot;);
                        window.setTimeout(&quot;updateProgressBar(100);&quot;, 100);
                        document.getElementById(&quot;progressbarWrapper&quot;).style.display = &quot;none&quot;;
                        document.getElementById(&quot;status&quot;).style.display=&quot;none&quot;;
                    }
				} else {
					alert(req.statusText);
				}
            }
        }
	&lt;/script&gt;</pre></td></tr></table></div>

<h2>Style Code</h2>
<p>Now add the following code to the style section.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;link href=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css&quot; 
		rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&gt; 
		&lt;link href=&quot;style/ui.all.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&gt; 
		&lt;link href=&quot;style/ui.core.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&gt; 
		&lt;link href=&quot;style/ui.progressbar.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&gt; 
		&lt;style type=&quot;text/css&quot;&gt;
			.ui-progressbar-value { background-image: url(images/progressBarImage.jpg); }
			.backgroundClass
			{
				background-image: url(images/background.jpg);
				color:white;
			}
		&lt;/style&gt;</pre></td></tr></table></div>

<h2>Listener Code</h2>
<p>This listener will listen to the event of file upload and has a method called fileUpdate() which will be automatically invoked as and when there is an update on fileUpload.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package fileupload;
	import org.apache.commons.fileupload.ProgressListener;
	public class FileUploadListener implements ProgressListener{
		private volatile long bytesRead = 0L, contentLength = 0L, item = 0L;   
		public FileUploadListener() {
			super();
		}
&nbsp;
		public void update(long aBytesRead, long aContentLength, int anItem) {
			bytesRead = aBytesRead;
			contentLength = aContentLength;
			item = anItem;
		}
&nbsp;
		public long getBytesRead() {
			return bytesRead;
		}
&nbsp;
		public long getContentLength() {
			return contentLength;
		}
&nbsp;
		public long getItem() {
			return item;
		}
	}</pre></td></tr></table></div>

<h2>Servlet Code</h2>
<p>The servlet will get the information about the number of bytes read through the listener and will construct a response xml with tags &#8220;bytes-read&#8221; and &#8220;content-length&#8221; etc.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package fileupload;
&nbsp;
	import javax.servlet.Servlet;
	import javax.servlet.http.HttpServlet;
	import java.io.*;
	import java.util.*;
	import javax.servlet.http.*;
	import org.apache.commons.fileupload.*;
	import javax.servlet.ServletException;
	import org.apache.commons.fileupload.disk.DiskFileItemFactory;
	import org.apache.commons.fileupload.servlet.ServletFileUpload;
&nbsp;
	public class FileUploadServlet extends HttpServlet implements Servlet {
&nbsp;
	    private static final long serialVersionUID = 2740693677625051632L;
&nbsp;
	    public FileUploadServlet() {
	        super();
	    }
&nbsp;
		protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        PrintWriter out = response.getWriter();
		    HttpSession session = request.getSession();
	        FileUploadListener listener = null;
			StringBuffer buffy = new StringBuffer();
		    long bytesRead = 0, contentLength = 0;
&nbsp;
	        if (session == null) {
	            return;
		    } else if (session != null) {
	            listener = (FileUploadListener) session.getAttribute(&quot;LISTENER&quot;);
&nbsp;
		        if (listener == null) {
			        return;
	            } else {
		            bytesRead = listener.getBytesRead();
	                contentLength = listener.getContentLength();
		        }
	        }
&nbsp;
		    response.setContentType(&quot;text/xml&quot;);
&nbsp;
		    buffy.append(&quot;&lt;?xml version=\&quot;1.0\&quot; encoding=\&quot;ISO-8859-1\&quot;?&gt;\n&quot;);
			buffy.append(&quot;&lt;response&gt;\n&quot;);
	        buffy.append(&quot;\t&lt;bytes_read&gt;&quot; + bytesRead + &quot;&lt;/bytes_read&gt;\n&quot;);
	        buffy.append(&quot;\t&lt;content_length&gt;&quot; + contentLength + &quot;&lt;/content_length&gt;\n&quot;);
&nbsp;
	        if (bytesRead == contentLength) {
	            buffy.append(&quot;\t&lt;finished /&gt;\n&quot;);
		        session.setAttribute(&quot;LISTENER&quot;, null);
	        } else {
		        long percentComplete = ((100 * bytesRead) / contentLength);
	            buffy.append(&quot;\t&lt;percent_complete&gt;&quot; + percentComplete + &quot;&lt;/percent_complete&gt;\n&quot;);
		    }
	        buffy.append(&quot;&lt;/response&gt;\n&quot;);
		    out.println(buffy.toString());
	        out.flush();
		    out.close();
	    }
&nbsp;
		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        FileItemFactory factory = new DiskFileItemFactory();
		    ServletFileUpload upload = new ServletFileUpload(factory);
	        FileUploadListener listener = new FileUploadListener();
		    HttpSession session = request.getSession();
			session.setAttribute(&quot;LISTENER&quot;, listener);
	        upload.setProgressListener(listener);
		    List uploadedItems = null;
			FileItem fileItem = null;
	        String filePath = &quot;c:\\temp&quot;;
&nbsp;
		    try {
			    uploadedItems = upload.parseRequest(request);
	            Iterator i = uploadedItems.iterator();
&nbsp;
		        while (i.hasNext()) {
			        fileItem = (FileItem) i.next();
				    if (fileItem.isFormField() == false) {
					    if (fileItem.getSize() &gt; 0) {
						    File uploadedFile = null;
							String myFullFileName = fileItem.getName(), myFileName = &quot;&quot;, slashType = (myFullFileName.lastIndexOf(&quot;\\&quot;) &gt; 0) ? &quot;\\&quot; : &quot;/&quot;;
	                        int startIndex = myFullFileName.lastIndexOf(slashType);
		                    myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
			                uploadedFile = new File(filePath, myFileName);
				            fileItem.write(uploadedFile);
					    }
	                }
		        }
			} catch (FileUploadException e) {
	            e.printStackTrace();
		    } catch (Exception e) {
			    e.printStackTrace();
	        }
		}
	}</pre></td></tr></table></div>

<h2>web.xml</h2>
<p>We need to declare the servlet and also the listener in web.xml.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;servlet&gt;
		&lt;servlet-name&gt;UploadServlet &lt;/servlet-name&gt;
		&lt;servlet-class&gt;fileupload.FileUploadServlet&lt;/servlet-class&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;UploadServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/example/FileUploadServlet&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;listener&gt;
		&lt;listener-class&gt;fileupload.FileUploadListener&lt;/listener-class&gt;
	&lt;/listener&gt;</pre></td></tr></table></div>

<h2>Conclusion</h2>
<p>In this tutorial , we have seen how to upload a file when we have java on the server side.<br />
We have also seen how to do the same using jQuery-Ajax and jQuery progress bar.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/03/asynchronous-file-upload-using-ajax-jquery-progress-bar-and-java/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using YUI to attach JavaScript event listeners</title>
		<link>http://www.javabeat.net/2011/01/using-yui-to-attach-javascript-event-listeners/</link>
		<comments>http://www.javabeat.net/2011/01/using-yui-to-attach-javascript-event-listeners/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 15:26:39 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1472</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Yahoo User Interface 2.X CookbookWelcome to Yahoo User Interface 2.x Cookbook. The Yahoo! User Interface (YUI) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML, and AJAX. Although you can create stylish Internet applications by modifying its default components, even [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><center><strong>Yahoo User Interface 2.X Cookbook</strong></center>Welcome to Yahoo User Interface 2.x Cookbook. The Yahoo! User Interface (<strong>YUI</strong>) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as <strong>DOM</strong> scripting, DHTML, and <strong>AJAX</strong>. Although you can create stylish Internet applications by modifying its default components, even advanced users find it challenging to create impressive feature-rich Internet applications using <strong>YUI</strong>.</p>
<p>This book will help you learn how to use <strong>YUI</strong> 2.x to build richer, more interactive web applications that impress clients and wow your friends. It starts by explaining the core features of <strong>YUI</strong> 2.x, the utilities that the rest of the library depends on and that will make your life easier. It then explains how to build UI components and make <strong>AJAX</strong> requests using the <strong>YUI</strong> framework. Each recipe will cover the most common ways to use a component and how to configure it, and then explain any other features that may be available. We wrap things up by looking at some of the recent beta components and explain how to use them, and how they may be useful on your web application.</p>
<p><strong>What This Book Covers</strong></p>
<p>Chapter 1: Using <strong>YUI</strong> 2.x, teaches various techniques for including <strong>YUI</strong> into your project, and how to use the Get, Cookie, and <strong>JSON</strong> utilities.</p>
<p>Chapter 2: Using <strong>DOM</strong> and Selector Components, teaches how to use the <strong>DOM</strong> and Selector components to fetch and manipulate <strong>DOM</strong> elements.</p>
<p>Chapter 3: Using Event Component, teaches how to attach events to <strong>DOM</strong> elements and how to use the powerful custom event system to create your own events.</p>
<p>Chapter 4: Using Connection Component, teaches how to make <strong>AJAX </strong> requests with <strong>YUI</strong> and subscribe to related events.</p>
<p>Chapter 5: Using DataSource Component, teaches how to abstract away sources of data with a powerful and easy to use interface.</p>
<p>Chapter 6: Using Logger and <strong>YUI</strong> Test Components, teaches how to use <strong>YUI</strong> to log <strong>JavaScript</strong> and then how to test your <strong>JavaScript</strong> applications.</p>
<p>Chapter 7: Using Element and Button Components, teaches how to leverage Element to simplify working with <strong>DOM</strong> elements, and Button to simplify working with Button elements.</p>
<p>Chapter 8: Using Menu Component, teaches how to create and manage Menu objects.</p>
<p>Chapter 9: Using Animation Component, teaches how to use <strong>YUI</strong> to animate <strong>DOM</strong> elements.</p>
<p>Chapter 10: Using Drag and Drop Component, teaches how to use the Drag and Drop utility.</p>
<p>Chapter 11: Using Container Component, teaches all about the container stack and the various widgets that make use of it.</p>
<p>Chapter 12: Using DataTable Component, teaches how to use DataTable to build more useful and interactable tables.</p>
<p>Chapter 13: Using TreeView Component, teaches how to use TreeView to organize hierarchical data.</p>
<p>Chapter 14: Other Useful Components, teaches the basics about some of the other well established widgets, such as Autocomplete and Slider.</p>
<p>Chapter 15: Some Interesting Beta Components, teaches the basics about some of the latest widgets, such as Storage and Charts.</p>
<h2 style="text-align: center;"><span style="text-decoration: underline;"><span style="color: #000080; text-decoration: underline;">Using Event Component</span></span></h2>
<p>In this chapter, we will cover:</p>
<ul>
<li>Using <strong>YUI</strong> to attach <strong>JavaScript</strong> event listeners</li>
<li>Event normalization functions</li>
<li>Removing event listeners</li>
<li>Listening for key events</li>
<li>Using special <strong>YUI</strong>-only events</li>
<li>Using <strong>YUI</strong> helper functions</li>
<li>Using custom events</li>
<li>The simple way to add custom events to classes</li>
</ul>
<p><span style="font-size: 13px;">In this chapter, you will learn how to use </span><strong style="font-size: 13px;">YUI</strong><span style="font-size: 13px;"> to handle </span><strong style="font-size: 13px;">JavaScript</strong><span style="font-size: 13px;"> events, what special events </span><strong style="font-size: 13px;">YUI</strong><span style="font-size: 13px;"> has to improve the functionality of some </span><strong style="font-size: 13px;">JavaScript</strong><span style="font-size: 13px;"> events, and how to write custom events for your own application.</span></p>
<h2>Using <strong>YUI</strong> to attach <strong>JavaScript</strong> event listeners</h2>
<p>When attaching events in <strong>JavaScript</strong> most browsers use the addEventListener function, but the developers of IE use a function called attachEvent. Legacy browsers do not support either function, but instead require developers to attach functions directly to element objects using the &#8216;on&#8217; + eventName property (for example myElement.onclick=function(){&#8230;}).</p>
<p>Additionally, the execution context of event callback functions varies depending on how the event listener is attached. The Event component normalizes all the cross-browser issues, fixes the execution context of the callback function, and provides additional event improvements. This recipe will show how to attach <strong>JavaScript</strong> event listeners, using <strong>YUI</strong>.</p>
<h2>How to do it&#8230;</h2>
<p>Attach a click event to an element:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e) {
		alert(&quot;myElementId was clicked&quot;);
	};
	YAHOO.util.Event.addListener(myElement, 'click', fnCallback);</pre>
<p>Attach a click event to an element by its ID:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;myElementId was clicked&quot;);
	};
	YAHOO.util.Event.addListener('myElementId','click',fnCallback)</pre>
<p>Attach a click event to several elements at once:</p>
<pre class="brush: java; title: ; notranslate">var ids = [&quot;myElementId1&quot;, &quot;myElementId2&quot;, &quot;myElementId3&quot;];
	var fnCallback = function(e) {
		var targ = YAHOO.util.Event.getTarget(e);
		alert(targ.id + &quot; was clicked&quot;);
	};
	YAHOO.util.Event.addListener(ids, 'click', fnCallback);</pre>
<p>When attaching event listeners, you can provide an object as the optional fourth argument, to be passed through as the second argument to the callback function:</p>
<pre class="brush: java; title: ; notranslate">var myElem = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e, obj) {
		alert(obj);
	};
	var obj = &quot;I was passed through.&quot;;
	YAHOO.util.Event.addListener(myElem,'click',fnCallback,obj);</pre>
<p>When attaching event listeners, you can change the execution context of the callback function to the fourth argument, by passing true as the optional fi fth argument:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e) {
		alert('My execution context was changed.');
	};
	var ctx = {
		/* some object to be the execution context of callback */
	};
	YAHOO.util.Event.addListener(
		myElement, 'click', fnCallback, ctx, true);</pre>
<h2>How it works&#8230;</h2>
<p>The addListener function wraps the native event handling functions, normalizing the crossbrowser differences. When attaching events, <strong>YUI</strong> calls the correct browser specifi c function, or defaults to legacy event handlers. Before executing the callback function, the Event component must (in some browsers) fi nd the event object and adjust the execution context of the callback function. The callback function is normalized by wrapping it in a closure function that executes when the browser event fi res, thereby allowing <strong><a href="http://www.javabeat.net/books/yui/1/">YUI</a></strong> to correct the event, before actually executing the callback function.</p>
<p>In legacy browsers, which can only have one callback function per event type, <strong>YUI</strong> attaches a callback function that iterates through the listeners attached by the addListener function.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The addListener function returns true if the event listener is attached successfully and false otherwise.</p>
<p>If the element to listen on is not available when the addListener function is called, the function will poll the <strong>DOM</strong> and wait to attach the listener when the element becomes available.</p>
<p>Additionally, the Event component also keeps a list of all events that it has attached. This list is maintained to simplify removing events listeners, and so that all event listeners can be removed when the end-user leaves the page.</p>
<p>Find all events attached to an element:</p>
<pre class="brush: java; title: ; notranslate">var listeners = YAHOO.util.Event.getListeners('myElementId');
	for (var i=0,j=listeners.length; i&lt;j; i+=1) {
		var listener = listeners[i];
		alert(listener.type); // event type
		alert(listener.fn); // callback function
		alert(listener.obj); // second argument of callback
		alert(listener.adjust); // execution context
	}</pre>
<p>Find all events of a certain type attached to an element:</p>
<pre class="brush: java; title: ; notranslate">// only click listeners
	var listeners =
		YAHOO.util.Event.getListeners('myElementId', 'click');

		The garbage collector in JavaScript does not always do a good job cleaning up
		event handlers. When removing nodes from the DOM, remember to remove
		events you may have added as well.</pre>
<p>The garbage collector in <strong>JavaScript</strong> does not always do a good job cleaning up event handlers. When removing nodes from the <strong>DOM</strong>, remember to remove events you may have added as well.</p>
<h3>More on YAHOO.util.Event.addListener</h3>
<p>The addListener function has been aliased by the shorter on function:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e) {
		alert(&quot;myElementId was clicked&quot;);
	};
	YAHOO.util.Event.on(myElement, 'click', fnCallback);</pre>
<p>By passing an object in as the optional fifth argument of addListener, instead of a Boolean, you can change the execution context of the callback to that object, while still passing in an another object as the optional fourth argument:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e, obj) {
		// this executes in the context of 'ctx'
		alert(obj);
	};
	var obj = &quot;I was passed through.&quot;;
	var ctx = {
		/* some object to be the execution context of callback */
	};
	YAHOO.util.Event.addListener(
		myElement,'click',fnCallback,obj, ctx);</pre>
<p>Lastly, there is an optional Boolean value that can be provided as the sixth argument of addListener, which causes the callback to execute in the event capture phase, instead of the event bubbling phase. You probably won&#8217;t ever need to set this value to true, but if you want to learn more about <strong>JavaScript</strong> event phases see:</p>
<pre class="brush: java; title: ; notranslate">http://www.quirksmode.org/js/events_order.html</pre>
<h2>See also</h2>
<p>Refer to Removing event listeners, to learn about how to remove event callbacks when they are not longer needed.</p>
<h1>Event normalization functions</h1>
<p>The event object, provided as the first argument of the callback function, contains a variety of values that you may need to use (such as the target element, character code, etc.). <strong>YUI </strong>provides a collection of static functions that normalizes the cross-browser variations of these values. Before trying to use these properties, you should read this recipe, as it walks you through each of those functions.</p>
<h2>How to do it&#8230;</h2>
<p>Fetch the normalized target element of an event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var targetElement = YAHOO.util.Event.getTarget(e);
		alert(targetElement.id);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch the character code of a key event (also known as the key code):</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var charCode = YAHOO.util.Event.getCharCode(e);
		alert(charCode);
	};
	YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);</pre>
<p>Fetch the x and y coordinates of a mouse event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var x = YAHOO.util.Event.getPageX(e);
		var y = YAHOO.util.Event.getPageY(e);
		alert(&quot;x-position=&quot; + x + &quot; and x-position= &quot; + y);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch both the x and y coordinates of a mouse event, using:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var point = YAHOO.util.Event.getXY(e);
		alert(&quot;x-position=&quot;+point[0]+&quot; and x-position= &quot;+point[1]);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch the normalized related target element of an event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var targetElement = YAHOO.util.Event.getRelatedTarget(e);
		alert(targetElement.id);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch the normalized time of an event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var time = YAHOO.util.Event.getTime(e);
		alert(time);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Stop the default behavior, propagation (bubbling) of an event, or both:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		// prevents the event from bubbling up to ancestors
		YAHOO.util.Event.stopPropagation(e);
		// prevents the event's default
		YAHOO.util.Event.preventDefault(e);
		// prevents the event's default behavior and bubbling
		YAHOO.util.Event.stopEvent(e);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<h2>How it works&#8230;</h2>
<p>All of these functions test to see if a value exists on the event for each cross-browser variation of a property. The functions then normalize those values and return them. The stopPropogation and preventDefault functions actually modify the equivalent cross-browser property of the event, and delegate the behavior to the browsers.</p>
<h2>See also</h2>
<p>Refer to Using <strong>YUI</strong> helper functions, for information on event delegation, which can be used to improve the performance of events.</p>
<h2>Removing event listeners</h2>
<p>As with attaching listeners, there are two browser variations for removing events and legacy browser considerations as well. Additionally, when using the native event removal functions, you must pass in exactly the same arguments as you passed to the native add event functions. <strong>YUI</strong> not only handles the cross-browser variations, but ensures that you pass the correct arguments when removing a function. This recipe shows several ways to remove event listeners from elements.</p>
<h2>How to do it&#8230;</h2>
<p>Remove a callback function directly, by passing in the exact same arguments you used when calling addListener:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.removeListener('myElementId', 'click',
		fnCallback);</pre>
<p>Removing all events of a specific type does not require the arguments from addListener:</p>
<pre class="brush: java; title: ; notranslate">// removes all 'click' type events from 'myElementId'
	YAHOO.util.Event.removeListener('myElementId', 'click');</pre>
<p>Remove all listeners from an element:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.purgeElement('myElementId');</pre>
<p>Remove all listeners from an element and its descendant elements recursively:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.purgeElement('myElementId', true);</pre>
<p>Remove all events of a specific type from an element and its descendant elements recursively:</p>
<pre class="brush: java; title: ; notranslate">
// removes all 'click' type events
	YAHOO.util.Event.purgeElement('myElementId', true, 'click');
</pre>
<h2>How it works&#8230;</h2>
<p>In most cases <strong>YUI</strong> calls the native browser remove listener function, with the proper arguments from the internal array of listeners, and removes the listeners from its internal array. In legacy browsers, <strong>YUI</strong> simply deletes the function that was added to the event.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>Like the addListener function, the removeListener functions can accept either an element object or the id attribute of an element as its fi rst parameter. If the element cannot be found, <strong>YUI</strong> fails silently.</p>
<p>To prevent memory leaks and improve site performance, <strong>YUI</strong> attaches an unload event listener, which removes all event listeners when the page unloads. When removing nodes from the <strong>DOM</strong>, you should call purgeElement on any element that might (or whose descendant elements might) have events attached to them.</p>
<h2>Listening for key events</h2>
<p>The native browser support for key events is identical to other events, except in addition to the other properties, the character code is attached to the event object. There are several browser variations to where the character code is stored and some value discrepancies. <strong>YUI</strong> handles these cross-browser issues, as well as adding the ability to test for key combinations (such as &#8216;ctrl&#8217; plus another key), and a simplifi ed interface. This recipe explains how to listen for key events, and how to leverage the more powerful <strong>YUI</strong> key management functions.</p>
<h2>How to do it&#8230;</h2>
<p>Listen for the keypress event and fi nd the character code:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var charCode = YAHOO.util.Event.getCharCode(e);
		alert('Key pressed with character code ' + charCode);
	};
	YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);</pre>
<p>The event callback has some properties which are true when the Alt, Control, or Shift keys are pressed along with the triggering key:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		if (e.altKey) {
			alert(&quot;alt key was pressed as well&quot;);
		}
		if (e.ctrlKey) {
			alert(&quot;control key was pressed as well&quot;);
		}
		if (e.shiftKey) {
			alert(&quot;shift key was pressed as well&quot;);
		}
	};
	YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);</pre>
<p>Use the KeyListener function to effortlessly attach key events:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;The enter key was pressed&quot;);
	};
	var keyObj = {keys:13};
	var keyHandle =
		new YAHOO.util.KeyListener('myElemId', keyObj, fnCallback);
		keyHandle.enable();</pre>
<p>Use the KeyListener function to listen for several key events when Ctrl is also pressed:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;Up, Right, Down, or Left and Control was pressed&quot;);
	};
	var keyObj = {
		alt: false,
		ctrl: true,
		shift: false,
		keys: [37,38,39,40]
	};
	var keyHandle =
		new YAHOO.util.KeyListener('myElemId', keyObj, fnCallback);
	keyHandle.enable();</pre>
<p>The KeyListener function returns an object with two functions, enable and disabled, which allow you to turn the event listener on and off:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">// turn off the key listener
	keyHandle.disable();
	// turn on the key listener
	keyHandle.enable();</pre>
<h2>How it works&#8230;</h2>
<p>When subscribing to any key event directly, <strong>YUI</strong> behaves as it does with other events, wrapping the native event and handling-cross browser variations. The getCharCode function checks the event object for the browser variations of character code, and normalizes the value.</p>
<p>The KeyListener function wraps a keydown event with an instantiatable object that checks the character codes before executing the callback. The disable and enable functions of the returned object respectively call removeListener and addListener for you. You must call the enable function before the instantiated KeyListener to work.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The second argument of the KeyListener function is called the keyData object, and requires the keys property, but the Boolean values alt, ctrl, and shift are optional. The keys property can either be a single or an array of integer character codes.</p>
<p>By default the KeyListener function listens for the keydown event, but you can also specify the keyup event by passing it as a fourth optional argument:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;The escape key was keyed up&quot;);
	};
	var keyObj = {keys:27};
	var KeyListener = YAHOO.util.KeyListener;
	var keyHandle =
		new KeyListener('myElemId', keyObj, fnCallback, 'keyup');
	keyHandle.enable();</pre>
<p>Also, common key codes are available for you on a static object:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.KeyListener.KEY = {
		ALT : 18,
		BACK_SPACE : 8,
		CAPS_LOCK : 20,
		CONTROL : 17,
		DELETE : 46,
		DOWN : 40,
		END : 35,
		ENTER : 13,
		ESCAPE : 27,
		HOME : 36,
		LEFT : 37,
		META : 224,
		NUM_LOCK : 144,
		PAGE_DOWN : 34,
		PAGE_UP : 33,
		PAUSE : 19,
		PRINTSCREEN : 44,
		RIGHT : 39,
		SCROLL_LOCK : 145,
		SHIFT : 16,
		SPACE : 32,
		TAB : 9,
		UP : 38
	};</pre>
<h2>Using special YUI only events</h2>
<p>The Event component has two special events to bubble the focus and blur events, and two events that emulate IE&#8217;s mouseenter and mouseleave events. This recipe explains how to use each of these events.</p>
<h2>Getting ready</h2>
<p>Use the following <strong>DOM</strong> for the examples in this recipe:</p>
<pre class="brush: java; title: ; notranslate">&lt;div id=&quot;myElementId&quot;&gt;
		&lt;h3 id=&quot;myHeaderId&quot;&gt;Example Title&lt;/h3&gt;
		&lt;input name=&quot;myTextInput1&quot; type=&quot;text'/&gt;
		&lt;input name=&quot;myTextInput2&quot; type=&quot;text'/&gt;
		&lt;input name=&quot;myTextInput3&quot; type=&quot;text'/&gt;
	&lt;/div&gt;</pre>
<p>You will need to include the event-mouseenter optional component for the mouse events in this recipe:</p>
<pre class="brush: java; title: ; notranslate">&lt;script src=&quot;pathToBuild/event-mouseenter/event-mouseenter-min.js&quot;
		type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<h2>How to do it&#8230;</h2>
<p>Use the special focusin event to handle bubbling focus events:</p>
<pre class="brush: java; title: ; notranslate">// the focus of all 3 inputs can be handled by one callback
	YAHOO.util.Event.on(&quot;myElementId&quot;, &quot;focusin&quot;, function(e) {
		var targ = YAHOO.util.Event.getTarget(e);
		alert(&quot;focused on target: &quot; + targ.name);
	});</pre>
<p>Use the special focusout event to handle bubbling blur events:</p>
<pre class="brush: java; title: ; notranslate">// the blur of all 3 inputs can be handled by one callback
	YAHOO.util.Event.on(&quot;myElementId&quot;, &quot;focusout&quot;, function(e) {
		var targ = YAHOO.util.Event.getTarget(e);
		alert(&quot;blurred on target: &quot; + targ.name);
	});</pre>
<p>Use the mouseenter event to fi re an event once when the mouse first enters an element:</p>
<pre class="brush: java; title: ; notranslate">// this callback fire once when the mouse enters the p tag
	YAHOO.util.Event.on('myHeaderId', 'mouseenter', function(e){
		alert(&quot;Mouse entered: &quot; + this.id);
	});</pre>
<p>Use the mouseleave event to fi re an event once when the mouse first leaves an element:</p>
<pre class="brush: java; title: ; notranslate">// this callback fire once when the mouse enters the p tag
	YAHOO.util.Event.on('myHeaderId', 'mouseleave', function(e){
		YAHOO.log(&quot;Mouse left: &quot; + this.id);
	});</pre>
<h2>How it works&#8230;</h2>
<p>The focusin and focusout are special-cased events that leverage the capture phase of <strong>JavaScript</strong> events to emulate bubbling of blur and focus events.</p>
<p>The mouseenter and mouseleave events use IE&#8217;s native event of the same name, but in other browsers <strong>YUI</strong> adds listeners to the mouseover and mouseout events of an element to emulate the behavior. <strong>YUI</strong> removes or re-attaches these events as necessary, to minimize the number of event subscribers.</p>
<h2>Using YUI helper event functions</h2>
<p><strong>YUI</strong> events have four useful helpers functions: delegate, onAvailable, onContentReady, and onDOMReady. These functions augment how developers interact with the <strong>DOM</strong>. This recipe explains how they work.</p>
<h2>Getting ready</h2>
<p>To use the delegate function in this recipe, you will need to include the event-delegate and Selector components. Use the following <strong>DOM</strong> for the examples in this recipe:</p>
<pre class="brush: java; title: ; notranslate">&lt;div id=&quot;myElementId&quot;&gt;
		&lt;ul&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;link1&quot;&gt;Item Type One&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;link2&quot;&gt;Item Type Two&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;link3&quot;&gt;Item Type Three&lt;/a&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;</pre>
<h2>How to do it&#8230;</h2>
<p>Use event delegation to have a single handler for all three anchors:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.delegate(&quot;myElementId&quot;, &quot;click&quot;,
	function(e, matchedElement, container) {
		// The matchedElement is the default scope
		alert(&quot;Default scope id: &quot; + this.id);
		alert(&quot;Clicked link id: &quot; + matchedElement.id);
		/* The actual click target, which could be the matched item or a
		descendant of it. */
		alert(&quot;Event target: &quot; + YAHOO.util.Event.getTarget(e));
		// The delegation container is passed as a third argument
		alert(&quot;Delegation container: &quot; + container.id);
	}, &quot;li a&quot;);</pre>
<p>Remove event delegation with the removeDelegate function:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.removeDelegate(&quot;myElementId&quot;, &quot;click&quot;,
		fnCallback);</pre>
<p>Use onAvailable to fi re a function as soon as an element is detected in the <strong>DOM</strong>:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(obj) {
		alert('myElementId is now available');
	};
	var obj = {/* optional pass-through object */};
	YAHOO.util.Event.onAvailable('myElementId', fnCallback, obj);</pre>
<p>Use onContentReady to fi re a function as soon as an element and its nextSibling are<br />
detected in the <strong>DOM</strong>:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(obj) {
		// the execution context was changed to obj
		alert('myElementId is now ready');
	};
	var obj = {/* optional pass-through object */};
	YAHOO.util.Event.onContentReady('myElementId', fnCallback,
		obj, true);</pre>
<p>Fire a callback function as soon as the <strong>DOM</strong> has fi nished loading:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(obj) {
		// the execution context was changed to window
		alert('The DOM is now available');
	};
	var obj = {/* optional pass-through object */};
	YAHOO.util.Event.onDOMReady(fnCallback, obj, window);</pre>
<h2>How it works&#8230;</h2>
<p>Event delegation works by attaching one event listener, of the specifi ed type, to the container element (argument one). When the specifi ed event type fi res, anywhere on the container element, the <strong>DOM</strong> path from the event target to the container element is compared against the selector specifi ed as the fourth argument of the delegate function. If the selector matches, then the callback function is executed.</p>
<p>The onAvailable and onContentReady functions poll the DOM until the element is available by document.getElementById or the window load event isfired. The onContentReady function only differs from onAvailable, in that it waits until the nextSibling of the element is also available to ensure that its descendants have completely loaded.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The onAvailable and onContentReady functions have signatures exactly like the addListener function, except without the event type. You can use both functions after the window load event fi res, and they will poll the <strong>DOM</strong> for up to 10 seconds.</p>
<p>The onDOMReady function also shares a signature with addListener, except without the element and event type. The recipes for these three functions show the variations you could use for the optional fourth and fi fth arguments.</p>
<pre class="brush: java; title: ; notranslate">Attaching fewer events to the DOM improves the performance of your
	site. Use the event delegation function as much as possible to reduce
	the number of event listeners.</pre>
<h2>See also</h2>
<p>Refer to Using <strong>YUI</strong> to attach <strong>JavaScript</strong> event listeners, for more information on the optional arguments for onAvailable and onContentReady.</p>
<h2>Using custom events</h2>
<p><strong>YUI</strong> provides a framework for publishing and fi ring arbitrary events that you create. This simple feature drives much of the framework, and is the basis for most of the more complicated widgets covered in this book. This recipe shows you how to create, subscribe to, and fire custom events.</p>
<h2>How to do it&#8230;</h2>
<p>Create a basic custom event:</p>
<pre class="brush: java; title: ; notranslate">var myEvent =	new YAHOO.util.CustomEvent('myEvent');</pre>
<p>Create a custom event, whose callback has the specifi ed execution context:</p>
<pre class="brush: java; title: ; notranslate">var ctx = {};
	var myEvent = new YAHOO.util.CustomEvent('myEvent', ctx);</pre>
<p>Subscribe to a custom event:</p>
<pre class="brush: java; title: ; notranslate">var myCallback = function(eventName, fireArgs, obj) {
		/* … */
	};
	myEvent.subscribe(myCallback);</pre>
<p>Fire a custom event:</p>
<pre class="brush: java; title: ; notranslate">myEvent.fire();</pre>
<p>Unsubscribe one callback from a custom event:</p>
<pre class="brush: java; title: ; notranslate">// the signature is the same as the subscribe function
	if (myEvent.unsubscribe(myCallback)) {
		alert('callback unsubscribed successfully');
	}</pre>
<p>Unsubscribe all callbacks from a custom event:</p>
<pre class="brush: java; title: ; notranslate">myEvent.unsubscribeAll();</pre>
<h2>How it works&#8230;</h2>
<p>The custom event framework maintains an array of all instantiated custom events, and an object to map the event names to the custom event object. Custom event objects contain a list of subscriber callback functions, logic to handle scope normalization, and logic for passing parameters from its constructor, subscribe, and fire functions to each subscriber function. The unsubscribe function removes the specifi ed function by comparing the provided function against each subscriber function, and unsubscribeAll will truncate the array of subscriber functions.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>When calling the fire function of a custom event (and using the default callback signature), you can pass any number of arguments into the fire function, and they will be passed as an array to the second argument of each subscriber function.</p>
<p>When calling the unsubscribe function you should pass it the same signature as well calling the subscribe function to ensure the removal of the correct subscriber function.</p>
<p>The following subsections explain optional arguments that can be provided for the functions discussed in this recipe:</p>
<h3>Instantiation function arguments</h3>
<p>When instantiating a CustomEvent object, you need to only provide the fi rst argument, which is the event name, but you can provide up to four additional arguments:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/1.jpg"><img class="aligncenter size-medium wp-image-1474" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/1-300x128.jpg" width="300" height="128" /></a></p>
<p><center></center>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">var myEvent = YAHOO.util.CustomEvent('myEvent', this, false, YAHOO.
	util.CustomEvent.LIST, false);</pre>
<h3>Subscribe function</h3>
<p>When calling the subscribe function you must pass a required callback function as the first argument, but can also pass up to two additional arguments:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/2.jpg"><img class="aligncenter size-medium wp-image-1475" title="2" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/2-300x54.jpg" width="300" height="54" /></a></p>
<p><center></center>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">var newContext = { /* … */ };
	var obj = { /* … */ };
	var myCallback = function(type, fireArgs, obj) {
		/* … */
	}
	myEvent.subscribe(myCallback, obj, newContext);</pre>
<h3>Subscriber callback functions</h3>
<p>When the signature is CustomEvent.LIST (the default value) the following arguments will be passed to the subscriber callback functions when the custom event is fi red:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/3.jpg"><img class="aligncenter size-medium wp-image-1476" title="3" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/3-300x69.jpg" width="300" height="69" /></a></p>
<p><center></center>When the signature is CustomEvent.FLAT the following arguments will be passed:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/4.jpg"><img class="aligncenter size-medium wp-image-1477" title="4" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/4-300x64.jpg" width="300" height="64" /></a></p>
<h2>See also</h2>
<p>Refer to Apply EventProvider to manage custom events on objects for information on how to more effectively use custom events with objects.</p>
<h1>The simple way to add custom events to classes</h1>
<p>Since custom events drive much of the <strong>YUI</strong> framework, the developers have created the YAHOO.util.EventProvider class to simplify interacting with custom events on classes.<br />
This recipe explains how to apply EventProvider to your classes and leverage its subscription model.</p>
<h2>How to do it&#8230;</h2>
<p>Apply EventProvider to your class:</p>
<pre class="brush: java; title: ; notranslate">var MyClass = function() {/* … */};
	MyClass.prototype = {/* … */};
	YAHOO.lang.augment(MyClass, YAHOO.util.EventProvider);
	var myClassInst = new MyClass();</pre>
<p>Create an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.createEvent('myEvent');</pre>
<p>Subscribe to an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">var myCallback = function() {/* … */};
	myClassInst.subscribe('myEvent', myCallback);</pre>
<p>Test if an event has been created on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">if (myClassInst .hasEvent('myEvent')) {
		alert('myEvent has been created');
	}</pre>
<p>Fire an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.fireEvent('myEvent');</pre>
<p>Unsubscribe a callback from an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.unsubscribe('myEvent', myCallback);</pre>
<p>Unsubscribe from all callbacks from an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.unsubscribeAll('myEvent');</pre>
<p>Unsubscribe all events on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.unsubscribeAll();</pre>
<h2>How it works&#8230;</h2>
<p>When creating an event using the EventProvider framework, <strong>YUI</strong> prefaces the event name with a unique ID, so that custom event names are unique per object. Thus fi ring a custom event called myEvent on object A, does not execute callbacks subscribing to myEvent on object B. Otherwise, the functions work like their counterparts from the previous recipe, except they require you to specify the event name as the fi rst argument. The only exception to this rule is the fireEvent function , which calls the subscriber functions using the CustomEvent.FLAT argument signature, instead of CustomEvent.LIST.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The createEvent function will return the CustomEvent object that it creates or a previously existing one with the same name. The createEvent function instantiates the custom event object and hence you have less control over the instantiation arguments. However, you can pass a confi guration object as the second optional argument of createEvent, with the following properties:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/5.jpg"><img class="aligncenter size-medium wp-image-1473" title="5" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/5-300x120.jpg" width="300" height="120" /></a></p>
<p><center></center>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">Any subscriber functions applied using the subscribe function
	before calling the createEvent function will be lost. Make sure,
	when instantiating classes you made, that you create all events the
	class may use.</pre>
<h2>See also</h2>
<p>Using custom events, for more information on optional arguments that can be passed to the event functions.</p>
<p>The extending <strong>JavaScript</strong> objects, the <strong>YUI</strong> way, for more information on how to create your own extendable <strong>JavaScript</strong> objects.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/01/using-yui-to-attach-javascript-event-listeners/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Comet and Reverse AJAX</title>
		<link>http://www.javabeat.net/2010/09/introduction-to-comet-and-reverse-ajax/</link>
		<comments>http://www.javabeat.net/2010/09/introduction-to-comet-and-reverse-ajax/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 01:14:06 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Comet]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=503</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction It’s an era of Web 2.0. Most of the web applications are following the web 2.0 standards. AJAX played a major role in promoting web 2.0 applications and it had a great role in enhancing the user experience of a web applications. Comet challenges the request-response model in HTTP and allows the server to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>It’s an era of <strong>Web 2.0</strong>. Most of the web applications are following the <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=45" target="_blank">web 2.0</a> standards. <strong><a href="http://www.javabeat.net/articles/ajax/1/">AJAX</a></strong> played a major role in promoting web 2.0 applications and it had a great role in enhancing the user experience of a web applications.</p>
<p><strong>Comet</strong> challenges the request-response model in HTTP and allows the server to decide when it should send the data to client, usually referred to as &#8220;Server-Push&#8221;. <strong>Comet</strong> or Reverse AJAX is a technology that initiates exchange of data from the server to the client whenever there is any update in the server. <strong>Comet</strong> is expected to change the next generation web.</p>
<p>To understand the concept behind <strong>Comet</strong> you need to know the HTTP limitation and <strong>AJAX</strong>.</p>
<p><center>Buy <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=38" target="_blank">AJAX Books</a> from <a href="http://astore.amazon.com/javabeat-20" target="_blank">Java Books</a> Store</center></p>
<h2>HTTP Limitations</h2>
<p>In a web application the communication between client and server is always originated by the client and not by the server following the &#8220;request-response model&#8221;. It is not possible for any server to send the response to the client without having received the request from the client.</p>
<p>Consider the web application that gives the online cricket score. The page in the client browser should be refreshed / reloaded to view the modified score though the updation might have happened on the server much before the client raises the request to reload. Is there is any way to send the updated data from server to client without the client request? We will discuss it shortly.</p>
<p>In a web application the connection between client and server is NOT maintained. Since HTTP is following disconnected architecture the architects were forced to look for alternate way to identify the client uniquely. HTTP session helps the developers to overcome the disconnected architecture of HTTP in order to identify the user. Session handling is supported by all the server side technologies and web servers.</p>
<h2>AJAX – A Technology For Second Generation Of Web (web 2.0)</h2>
<p>AJAX is a set of technologies that allows the web programmers to create interactive web interface on web pages. In simple words AJAX helps in developing web application interfaces that works just like a desktop application. In typical web applications, the client sends a request to server and server sends the entire page content as response. On the other hand, AJAX based applications can interact with the server in the background and load only the required data in the page instead of refreshing the entire page. AJAX is following HTTP request-response model and the client need to initiate the communication using a JavaScript code.</p>
<p>However, even with AJAX the client is still forced to send the request to the server.</p>
<p>&#8220;Reverse AJAX&#8221; is term used to describe a web application where the server initiates the communication to the client.</p>
<h2>Introduction to Comet and Reverse AJAX</h2>
<p>AJAX based applications are becoming the de facto technology for architecting the web applications. AJAX allows the browsers to request data from the web server. However this does not enable the web server to respond without received any request from the browser.</p>
<p><strong>Comet</strong> is capable of solving this issue by enabling the web servers to asynchronously push the data to clients through a single, previously opened connection. This approach was unheard previously with web applications. The <strong>Comet</strong> style applications can send the latest data from the server to client with negligible latency.</p>
<p><strong>Comet</strong> helps us to develop different type of multi-user collaborative and monitoring web applications. This is impossible to develop without client side plugins. <strong>Comet</strong> keeps the clients synchronized with the server which might be changing frequently.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>AJAX improves the dynamism of a User interface for a single user, and for getting the modified data the browser is forced to make asynchronous request the server. The browser has to wait until the server performs some actions which internally make a request to server and displays the modified data. Since the web is a multi-user system, which is certain that some of the AJAX based applications might suffer transparency hurdles for users. If the same application can be implemented with the <strong>Comet</strong> technology, it can avoid the issues by pushing the latest updates to all clients. AJAX is responsible for improving single user responsiveness and <strong>Comet</strong> is responsible for the improving responsiveness for multi-user, collaborative web applications.</p>
<h2>Where you can use comet</h2>
<p><strong>Comet</strong> is NOT fit for all kind of web applications. <strong>Comet</strong> can be used in the following situations.</p>
<ul>
<li>If your application collaborates on shared data</li>
<li>If the users are getting advantage using the updated data from the server</li>
<li>If the user is spending long time on a single page</li>
</ul>
<h2>Scalability of Comet Web Application</h2>
<p><strong>Comet</strong> requires an open connection per client session on the underlying HTTP protocol. In most of the browsers the number of concurrent connection to a domain is limited to two. With <strong>Comet</strong> you need to keep one open connection to a server for a longer period of time. Under the standard Servlet life cycle, this is NOT a scalable model because each connection requires one thread on the Servlet. To overcome this limitation most of the application servers support Asynchronous Request Processing (ARP). In ARP a thread-pool is used to service the asynchronous request. ARP is using non-blocking IO technique for building highly scalable communications.</p>
<h2>Comet and Reverse AJAX frameworks</h2>
<p>When AJAX was introduced it was a roll-your-own solution, and you have to take care of browser dependency, XmlHTTPRequest object, generating request and parsing and displaying the responses. Nowadays many AJAX frameworks are available eliminating all the worries about building AJAX applications. Fortunately a lot of frameworks and servers are available for implementing <strong>Comet</strong>-style application. Let us discuss some of the frameworks which can help us in implementing the <strong>Comet</strong> style applications.</p>
<ul>
<li><strong>DWR 2.0</strong></li>
<li><strong>Grizzly Comet API</strong></li>
<li><strong>Atmosphere</strong></li>
<li><strong>AJAX push with ICEfaces</strong></li>
<li><strong>Asynchronous Servlet using Servlet 3.0</strong></li>
</ul>
<h3>DWR 2.0</h3>
<p><strong><a href="http://www.javabeat.net/articles/87-dwr-java-ajax-applications-1.html">DWR</a></strong> is an open source framework to implement <strong>AJAX</strong> using Java. The most easy-to-use <strong>Comet</strong> implementation is available with <strong>DWR framework</strong>. The important feature of <strong>DWR 2.0</strong> is reverse <strong>AJAX</strong>. It helps you to send asynchronous data from server to client. It is possible with the help of JavaScript API’s available at the client side.</p>
<h3>Grizzly Comet API</h3>
<p>The new Sun glassfish web server comes with <strong>Grizzly HTTP</strong> engine to support <strong>Comet</strong>. It avoids blocking HTTP connections by using asynchronous request process, otherwise the server need to make a permanent connection to server for <strong>Comet</strong> communication. This affects the scalability of <strong>Comet</strong> web application. Grizzly ensures greater performance by Asynchronous request processing which makes use of the thread pool system. Grizzly’s support includes a small set of API that makes it easy to develop <strong>Comet</strong> web application without any hazards.</p>
<h3>Atmosphere</h3>
<p>Atmosphere is a <strong>Comet</strong> framework which can work on any JEE web server. It is a POJO based framework and developers can create <strong>Comet</strong> web application without the help of Servlet 3.0 API. This framework includes several modules and helps us in implementing Bayeux protocol, Atmosphere runtime as well. The Framework contains its own web server called “Atmosphere Spade Server”. If you are using Atmosphere framework please be aware that only Jetty, GlashFish, and Grizzly servers can make use of asynchronous native API. The other webservers using the blocking IO approach and hence the application is NOT scalable.</p>
<h3>AJAX push with ICEfaces</h3>
<p>It is an open source <strong>AJAX</strong> based framework for developing Rich Internet Applications using Java. <strong>AJAX</strong> push is an exciting feature of ICEfaces which enable us to develop <strong>Comet</strong> web application with simple Java API without worrying about the low-level details of the push-mechanism. ICEfaces uses &#8220;long polling&#8221; to communicate from server to client. This involves holding an open connection from client to server with a blocking request, and then sends the response only when some state change in the application.</p>
<h3>Asynchronous Servlet using Servlet 3.0</h3>
<p>The new feature added with <strong>Servlet 3.0</strong> supports <strong>Comet</strong> style of application development. With Servlet 3.0 we can write portable <strong>Comet</strong> web applications. The asynchronous feature provides great design ideas to multiple vendors and provides a portable solution for the thread usage in <strong>Comet</strong> web application. APIs are available for easy implementation of <strong>Comet</strong> and supported by various containers. It also provides support for suspending a request and resume later. The suspended request can access the resource and like access to a database or wait for a response from web service. The resumed request can be re-dispatched through the filter for processing. Notifications are available to the developers regarding the status of suspend, resume and complete.</p>
<h2>Conclusion</h2>
<p>Comet is making wonders in web applications by using mechanisms unspecified by web standards. Going forward comet has the potential to become standardization. Today if you look at AJAX using XHR is universally supported. Comet-style web applications can bring a new way of creating interactive and collaborative web applications. It also puts complex challenges for implementing comet-style web applications in large scale. However, most of the web servers are providing stable and mature technology for implementing Comet. Let us hope that in future Comet become a standard for building web application and we can easily create cross-platform, portable and scalable Comet web application.</p>
<h2>Acknowledgement</h2>
<p>I would like to thank my manager Mr. Rajagopalan P, Principal, Education and Research Department, Infosys for the guidance and continuous support. I would like to thank Mr. Satheesha B N, Associate Vice-President, Education and Research Department, Infosys for motivating me to write this article. I would like to thank Mrs. Yuvarani, Lead, Education and Research Department, Infosys for giving valuable suggestions.</p>
<h2>AJAX Articles</h2>
<ul>
<li>Buy <a href="http://astore.amazon.com/javabeat-20?_encoding=UTF8&amp;node=38" target="_blank">AJAX Books</a> from <a href="http://astore.amazon.com/javabeat-20" target="_blank">Java Books</a> Store</li>
<li><a href="http://www.javabeat.net/articles/ajax/1/	">AJAX Articles</a></li>
<li><a href="http://www.javabeat.net/articles/87-dwr-java-ajax-applications-1.html">DWR Java AJAX Applications</a></li>
<li><a href="http://www.javabeat.net/articles/28-google-web-toolkitgwt-1.html">Google Web ToolKit(GWT)</a></li>
<li><a href="http://www.javabeat.net/articles/23-using-jsf-and-ajax-with-ajax150enabled-jsf-implement-1.html">Using JSF and AJAX</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/09/introduction-to-comet-and-reverse-ajax/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>AJAX and PHP</title>
		<link>http://www.javabeat.net/2010/06/ajax-and-php/</link>
		<comments>http://www.javabeat.net/2010/06/ajax-and-php/#comments</comments>
		<pubDate>Mon, 07 Jun 2010 00:17:48 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1946</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>AJAX and PHP Building Modern Web Applications – Second Edition AJAX is a complex phenomenon that means different things to different people. Computer users appreciate that their favorite websites are now friendlier and feel more responsive. Web developers learn new skills that empower them to create sleek web applications with little effort. Indeed, everything sounds [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER><b>AJAX</b> and PHP</CENTER></H1><br />
<H1>Building Modern Web Applications – Second Edition</H1><br />
<P><b>AJAX</b> is a complex phenomenon that means different things to different people.<br />
Computer users appreciate that their favorite websites are now friendlier and feel more<br />
responsive. Web developers learn new skills that empower them to create sleek web<br />
applications with little effort. Indeed, everything sounds good about <b>AJAX</b>!</P><br />
<P>At its roots, <b>AJAX</b> is a mix of technologies that lets you get rid of the evil page reload,<br />
which represents the dead time when navigating from one page to another. Eliminating<br />
page reloads is just one step away from enabling more complex features into websites,<br />
such as real-time data validation, drag-and-drop, and other tasks that weren&#8217;t traditionally<br />
associated with web applications. Although the <b>AJAX</b> ingredients are mature (the<br />
XMLHttpRequest object, which is the heart of <b>AJAX</b>, was created by Microsoft in<br />
1999), their new role in the new wave of web trends is very young, and we&#8217;ll witness a<br />
number of changes before these technologies will be properly used to the best benefit of<br />
the end users.</P><br />
<P><b>AJAX</b> isn&#8217;t, of course, the answer to all the Web&#8217;s problems, as the current hype around it<br />
may suggest. As with any other technology, <b>AJAX</b> can be overused, or used the wrong<br />
way. <b>AJAX</b> also comes with problems of its own: you need to fight with browser<br />
inconsistencies, <b>AJAX</b>-specific pages don&#8217;t work on browsers without JavaScript, they<br />
can&#8217;t be easily bookmarked by users, and search engines don&#8217;t always know how to parse<br />
them. Also, not everyone likes <b>AJAX</b>. While some are developing enterprise<br />
architectures using JavaScript, others prefer not to use it at all. When the hype is over,<br />
most will probably agree that the middle way is the wisest way to go for most scenarios.</P><br />
<P>In <I><b>AJAX</b> and PHP: Building Modern Web Applications – Second Edition</I>, we take a<br />
pragmatic and safe approach by teaching relevant patterns and best practices that we<br />
think any web developer will need sooner or later. We teach you how to avoid the<br />
common pitfalls, how to write efficient <b>AJAX</b> code, and how to achieve functionality that<br />
is easy to integrate into current and future web applications, without requiring you to<br />
rebuild the whole solution around <b>AJAX</b>. You&#8217;ll be able to use the knowledge you learn<br />
from this book right away, in your PHP web applications.</P><br />
<H1>What This Book Covers</H1><br />
<P><I>Chapter 1: The World of <b>AJAX</b> and PHP</I> is all about a quick introduction to the world of<br />
<b>AJAX</b>. In order to proceed with learning how to build <b>AJAX</b> applications, it&#8217;s important<br />
to understand why and where they are useful. It describes the XMLHttpRequest object,<br />
which is the key element that enables the client-side JavaScript code to call a page on the<br />
server asynchronously.</P><br />
<P><I>Chapter 2: JavaScript and the <b>AJAX</b> Client</I> walks you through many fields such as<br />
working with HTML, JavaScript, CSS, the DOM, XML, and XMLHttpRequest. It<br />
discusses the theory (and practice) that you will need to know to make these components<br />
come together smoothly, and form a solid foundation for your future <b>AJAX</b> applications.<br />
It also shows you how to implement simple error-handling techniques, and how to write<br />
code efficiently.</P><br />
<P><I>Chapter 3: Object Oriented JavaScript</I> covers a large area of what object-oriented<br />
programming means in the world of JavaScript starting from basic features and<br />
going far into the execution context of functions. It teaches you the basic OOP<br />
concepts—encapsulation, polymorphism, and inheritance, how to work with JavaScript<br />
objects, functions, classes, and prototypes, how to simulate private, instance, and static<br />
class members in JavaScript, what the JavaScript execution context is, how to implement<br />
inheritance by using constructor functions and prototyping, and the basics of JSON.</P><br />
<P><I>Chapter 4: Using PHP and MySQL on the Server</I> starts putting the server to work, using<br />
PHP to generate dynamic output, and MySQL to manipulate and store the backend data.<br />
This chapter shows you how to use XML and JSON with PHP (so that you can create<br />
server-side code that communicates with your JavaScript client), how to implement errorhandling<br />
code in your server-side PHP code, and how to work with MySQL databases.</P><br />
<P><I>Chapter 5: <b>AJAX</b> Form Validation</I> creates a form validation application that implements<br />
traditional techniques with added <b>AJAX</b> flavor, thereby making the form more userfriendly,<br />
responsive, and pleasing. The intention of this chapter isn&#8217;t to build the perfect<br />
validation technique but, rather, a working proof of concept that takes care of user input<br />
and ensures its validity.</P><br />
<P><I>Chapter 6: Debugging and Profiling <b>AJAX</b> Applications</I> teaches how to enable and use<br />
Internet Explorer&#8217;s debugging capabilities. It shows how you can work with Web<br />
Development Helper, Developer Toolbar, and other Internet Explorer tools and with<br />
Firefox plugins such as Firebug, Venkman JavaScript Debugger, and Web Developer.</P><br />
<P><I>Chapter 7: Advanced Patterns and Techniques</I> briefly covers some of the most important<br />
patterns and techniques covering usability, security, and techniques. Looking at methods,<br />
patterns, and techniques is so important that it has developed into its own science and has<br />
created a set of guidelines for typical problems that offer us predictable results.</P><br />
<P><I>Chapter 8: <b>AJAX</b> Chat with jQuery</I> teaches how to use <b>AJAX</b> to easily implement an<br />
online chat solution. This will also be your opportunity to use one of the most important<br />
JavaScript frameworks around—jQuery. More precisely, this chapter will explain the<br />
basics of jQuery and show how to create a simple, yet efficient clientserver chat<br />
mechanism using <b>AJAX</b>.</P><br />
<P><I>Chapter 9: <b>AJAX</b> Grid</I> explains the usage of an <b>AJAX</b>-enabled data grid plugin, jqGrid.</P><br />
<P><I>Appendix: Preparing Your Working Environment</I> covers the installation instructions that<br />
set up your machine for the exercises in this book. It also covers preparing the database<br />
that is used in many examples throughout the book.</P><br />
<H1><CENTER><b>AJAX</b> Form Validation</CENTER></H1><br />
<P>Input data validation is an essential feature for any modern software application.<br />
In the case of web applications, validation is an even more sensitive area because<br />
your application is widely reachable by many users with varying skill sets<br />
(and intentions).</P><br />
<P>Validation is not something that you can play with—invalid data has the potential<br />
to harm the application&#8217;s functionality, result in errant and inaccurate reporting, and<br />
even corrupt the application&#8217;s most sensitive area—the database.</P><br />
<P>Validating data requires checking whether the data entered by the user complies<br />
with rules established in accordance with the business rules of your application before<br />
allowing it to be used. For example, if dates must be entered in the YYYY-MM-DD<br />
format, then a date of February 28 would be invalid. Email addresses and phone<br />
numbers are other examples of data that should be checked against valid formats.<br />
In addition, validation must guard against &#8220;SQL injection&#8221;—which could corrupt,<br />
control, and/or access your data and database.</P><br />
<P><PRE><CODE><br />
	The importance of carefully defining input data validation rules<br />
	and consistently applying those rules cannot be overstated!<br />
</CODE></PRE></P><br />
<P>Historically, web form validation was implemented primarily on the server side,<br />
after the form was submitted. In some cases, on the client side, there was also some<br />
JavaScript code that performed simple validation such as checking whether the email<br />
address was valid or if a field had been left blank.</P><br />
<P>But, there were a few problems with traditional web form validation techniques:</P><br />
<UL><br />
<LI>Server-side form validation butted up against the limits of the HTTP<br />
protocol—a <I>stateless</I> protocol. Unless special code was written to deal with<br />
this issue, submitting a page with invalid data had the user receiving an<br />
empty form as a reply, and then, much to his chagrin, the entire form had to<br />
be filled in again from scratch. How annoying.</LI><br />
<LI>After submitting the page, the user waited (not so) patiently for a full-page<br />
reload. With every mistake made in filling out the form, the annoying &#8220;new<br />
page reload with blank form&#8221; happened.</LI><br />
</UL><br />
<P>In this chapter, we will create a form validation application that implements<br />
traditional techniques with added <b>AJAX</b> fl avor, thereby making the form more<br />
user-friendly, responsive, and pleasing. In the <b>AJAX</b> world, entered data is validated<br />
on the fl y, so the users are never confronted with waiting for full-page reloads or the<br />
rude &#8220;blank form&#8221; as a reply.</P><br />
<P>The server is the last line of defense against invalid data, so even if you implement<br />
client-side validation, server-side validation is mandatory. The JavaScript code that<br />
runs on the client can be disabled permanently from the browser&#8217;s settings and/or it<br />
can be easily modified or bypassed.</P><br />
<H1>Implementing <b>AJAX</b> form validation</H1><br />
<P>The form validation application we will build in this chapter validates the form at<br />
the server side on the classic form submit, implementing <b>AJAX</b> validation while the<br />
user navigates through the form. The final validation is performed at the server, as<br />
shown in Figure 5-1:</P><br />
<P><CENTER><IMG SRC="images/2010/06/Ajax-PHP/1.jpg"/></CENTER></P><br />
<P>Doing a final server-side validation when the form is submitted should never be<br />
considered optional. If someone disables JavaScript in the browser settings, <b>AJAX</b><br />
validation on the client side clearly won&#8217;t work, exposing sensitive data, and thereby<br />
allowing an evil-intentioned visitor to harm important data on the server (for<br />
example, through SQL injection).</P><br />
<P><PRE><CODE><br />
	Always validate user input on the server.<br />
</CODE></PRE></P><br />
<P>As shown in the preceding figure, the application you are about to build<br />
validates a registration form using both <b>AJAX</b> validation (client side) and typical<br />
server-side validation:</P><br />
<UL><br />
<LI><B><b>AJAX</b>-style</B> (client side): It happens when each form field loses focus<br />
(onblur). The field&#8217;s value is immediately sent to and evaluated by the<br />
server, which then returns a result (0 for failure, 1 for success). If validation<br />
fails, an error message will appear and notify the user about the failed<br />
validation, as shown in Figure 5-3.</LI><br />
<LI><B>PHP-style</B> (server side): This is the usual validation you would do on the<br />
server—checking user input against certain rules after the entire form is<br />
submitted. If no errors are found and the input data is valid, the browser<br />
is redirected to a success page, as shown in Figure 5-4. If validation fails,<br />
however, the user is sent back to the form page with the invalid fields<br />
highlighted, as shown in Figure 5-3.</LI><br />
</UL><br />
<P>Both <b>AJAX</b> validation and PHP validation check the entered data against our<br />
application&#8217;s rules:</P><br />
<UL><br />
<LI><B>Username</B> must not already exist in the database</LI><br />
<LI><B>Name field</B> cannot be empty</LI><br />
<LI>A gender must be selected</LI><br />
<LI><B>Month of birth</B> must be selected</LI><br />
<LI><B>Birthday</B> must be a valid date (between 1-31)</LI><br />
<LI><B>Year of birth</B> must be a valid year (between 1900-2000)</LI><br />
<LI>The date must exist in the number of days for each month (that is, there&#8217;s no<br />
February 31)</LI><br />
<LI><B>E-mail address</B> must be written in a valid email format</LI><br />
<LI><B>Phone number</B> must be written in standard US form: xxx-xxx-xxxx</LI><br />
<LI>The I&#8217;ve <B>read the Terms of Use</B> checkbox must be selected</LI><br />
</UL><br />
<P>Watch the application in action in the following screenshots:</P><br />
<P><CENTER><IMG SRC="images/2010/06/Ajax-PHP/2.jpg"/></CENTER></P><br />
<P><CENTER><IMG SRC="images/2010/06/Ajax-PHP/3.jpg"/></CENTER></P><br />
<P><CENTER><IMG SRC="images/2010/06/Ajax-PHP/4.jpg"/></CENTER></P></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/06/ajax-and-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CF AJAX Programming</title>
		<link>http://www.javabeat.net/2009/11/cf-ajax-programming/</link>
		<comments>http://www.javabeat.net/2009/11/cf-ajax-programming/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 00:42:04 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1967</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>ColdFusion 8 Developer Tutorial Adobe ColdFusion is an application server, renowned for rapid development of dynamic websites, with a straightforward language (CFML), powerful methods for packaging and reusing your code, and AJAX support that will get developers deep into powerful web applications quickly. This book is the most intense guide to creating professional ColdFusion applications [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER>ColdFusion 8 Developer Tutorial</CENTER></H1><br />
<P>Adobe ColdFusion is an application server, renowned for rapid development of dynamic<br />
websites, with a straightforward language (<B>CFML</B>), powerful methods for packaging and<br />
reusing your code, and AJAX support that will get developers deep into powerful web<br />
applications quickly.</P><br />
<P>This book is the most intense guide to creating professional ColdFusion applications<br />
available. Packed with example code, and written in a friendly, easy-to-read style, this<br />
book is just want you need if you are serious about ColdFusion.</P><br />
<P>This book will give you clear, concise and, of course, practical guidance to take you from<br />
the basics of ColdFusion 8 to the skills that will make you a ColdFusion developer to be<br />
reckoned with.</P><br />
<P>ColdFusion expert John Farrar will teach you about the basics of ColdFusion<br />
programming, application architecture, and object reuse, before showing you a range of<br />
topics including AJAX library integration, RESTful Web Services, PDF creation and<br />
manipulation, and dynamically generated presentation files that will make you the toast<br />
of your ColdFusion developer town.</P><br />
<P>This book digs deep with the basics, with real-world examples of the how and whys, to<br />
get more done faster with ColdFusion 8.</P><br />
<P>This book also covers the new features of ColdFusion 8 Update 1.</P><br />
<H1>What This Book Covers</H1><br />
<P><I>Chapter 1</I> describes how to enhance basic HTML pages with the power and simplicity of<br />
ColdFusion. It also explains the difference between static HTML pages and dynamic<br />
ColdFusion pages.</P><br />
<P><I>Chapter 2</I> describes how to create object classes and instantiate object instances. It also<br />
describes the object constructors. This chapter explains how to connect to a database<br />
through the internal methods of our objects.</P><br />
<P><I>Chapter 3</I> helps us in understanding how to manage multiple products through common<br />
forms for listing, editing, and adding data. This chapter explains integrating and<br />
streamlining the workflow of web forms and CFC database processing.</P><br />
<P>In <I>Chapter 4</I>, we will learn how to use the web server memory to create engaging and<br />
interactive web applications by using variable scopes. We will also learn how to share<br />
some information, and how to protect the rest of the information in a controlled manner.</P><br />
<P>In <I>Chapter 5</I>, we will learn about the basics of custom tags. We will also learn how to<br />
integrate cfinclude for libraries of segments. This chapter also includes skinning a<br />
website by using custom tags, the use of nested tags, and so on.</P><br />
<P><I>Chapter 6</I> includes wrapping of the ThickBox gallery functions into a custom tag for<br />
simple functional reuse and wrapping of a Google map library into our code with a<br />
custom tag for simplified interactive maps. This chapter helps us in understanding how to<br />
create a multi-state form list wrapped in a custom tag.</P><br />
<P>In <I>Chapter 7</I>, we will see how to use the authentication that comes standard with CF.<br />
This chapter explains how to control the site content based on current user permissions.</P><br />
<P>In <I>Chapter 8</I>, we will see how AJAX is different from HTML and regular server-oriented<br />
web pages. This chapter includes the comparison of HTML, server, and browser<br />
technology sites. It also explains about the ColdFusion widgets.</P><br />
<P>In <I>Chapter 9</I>, we will see the benefit received from the combined power of tag-based<br />
encapsulation with AJAX functionality.</P><br />
<P><I>Chapter 10</I> explains about binding, proxy connections, JSON features, Spry data<br />
integration, and debugging.</P><br />
<P>In <I>Chapter 11</I>, we will have a look at the different ways in which we can reorganize<br />
pages of PDF documents into a new PDF file from one or more separate PDF<br />
source documents.</P><br />
<P><I>Chapter 12</I> explains how to create Verity search collections, how to initialize the Verity<br />
indexes, how to interface with the indexes. This chapter also explains how to interface<br />
with PDF content for more control when calling documents.</P><br />
<P><I>Chapter 13</I> discusses files, emails, and images. This chapter helps in understanding how<br />
some of the common ColdFusion features empower developers to shift the web pages to<br />
web applications in many ways.</P><br />
<P>In <I>Chapter 14</I>, we will learn how to interact with other web servers and create features on<br />
our site that will allow others to interact with us.</P><br />
<P><I>Chapter 15</I> gives a broad introduction to ColdFusion&#8217;s way of generating dynamic<br />
reports. This chapter also gives a brief introduction to the ColdFusion Report<br />
Builder tool.</P><br />
<P><I>Chapter 16</I> shows the unique presentation capabilities built into ColdFusion. It gives<br />
practical examples to help build custom presentations with dynamic content on demand.</P><br />
<P><I>Appendix A</I> covers some important details of setting up a development environment. It<br />
also includes some important tips for better productivity.</P><br />
<P><I>Appendix B</I> includes some links and resources that are aimed at giving us a good starting<br />
base of information. It also explains a group of libaries that prove to be very significant.<br />
</P><br />
<P><br />
<H1><CENTER>CF AJAX Programming</CENTER></H1><br />
<P>This chapter deals with AJAX programming in ColdFusion. ColdFusion acts a great<br />
platform not just because of its code features, but because of its characteristics as<br />
to how the code interacts with other features. ColdFusion is a language with depth<br />
and power. Yet, as we developers know, it seems real power always requires a bit of<br />
custom code. In this chapter, we will have a look at the following topics:</P><br />
<UL><br />
<LI>Binding</LI><br />
<LI>Proxy connections</LI><br />
<LI>JSON features</LI><br />
<LI>Spry data integration</LI><br />
<LI>Debugging</LI><br />
</UL><br />
<H1>Binding</H1><br />
<P>When it comes to programming, the two most commonly used features are<br />
CFAJAXProxy and binding. The binding feature allows us to bind or tie things<br />
together by using a simpler technique than we would otherwise have needed<br />
to create. Binding acts as a double-ended connector in some scenarios. You can<br />
set the bind to pull data from another ColdFusion tag on the form. These must be<br />
AJAX tags with binding abilities.</P><br />
<P>There are four forms of bindings, on page, CFC, JavaScript, and URL. Let&#8217;s work<br />
through each style so that we will understand them well. We will start with on page<br />
binding. Remember that the tag has to support the binding. This is not a general<br />
ColdFusion feature, but we can use it wherever we desire.</P><br />
<H1>On Page Binding</H1><br />
<P>We are going to bind &#8216;cfdiv&#8217; to pull its content to show on page binding. We will set<br />
the value of a text input to the div. Refer to the following code. ColdFusion AJAX<br />
elements work in a manner different from how AJAX is written traditionally. It is<br />
more customary to name our browser-side HTML elements with id attributes. This<br />
is not the case with the binding features. As we can see in our code example, we<br />
have used the name attribute. We should remember to be case sensitive, since this is<br />
managed by JavaScript. When we run the code, we will notice that we must leave the<br />
input field before the browser registers that there has been a change in the value of<br />
the field. This is how the event model for the browser DOM works.</P><br />
<P><PRE><CODE><br />
	&lt;cfform id=&#8221;myForm&#8221; format=&#8221;html&#8221;&gt;<br />
		This is my edit box.&lt;br /&gt;<br />
		&lt;cfinput type=&#8221;text&#8221; name=&#8221;myText&#8221;&gt;<br />
	&lt;/cfform&gt;<br />
	&lt;hr /&gt;<br />
	And this is the bound div container.&lt;br /&gt;<br />
	&lt;cfdiv bind=&#8221;{myText}&#8221;&gt;&lt;/cfdiv&gt;<br />
</CODE></PRE></P><br />
<P>Notice how we use curly brackets to bind the value of the &#8216;myText&#8217; input box. This<br />
inserts the contents into &#8216;div&#8217; when the text box loses focus.</P></p>
<p><center><img src="images/2009/11/Ajax/1.jpg"/></center></p>
<p><P>This is an example of binding to in-page elements. If the binding we use is tied to a<br />
hidden window or tab, then the contents may not be updated.</P><br />
<H1>CFC Binding</H1><br />
<P>Now, we are going to bind our div to a CFC method. We will take the data that was<br />
being posted directly to the object, and then we will pass it out to the CFC. The CFC<br />
is going to repackage it, and send it back to the browser. The binding will enable the<br />
modified version of the content to be sent to the div. Refer to the following<br />
CFC code:</P><br />
<P><PRE><CODE><br />
	&lt;cfcomponent output=&#8221;false&#8221;&gt;<br />
		&lt;cffunction name=&#8221;getDivContent&#8221; returntype=&#8221;string&#8221;<br />
			access=&#8221;remote&#8221;&gt;<br />
			&lt;cfargument name=&#8221;edit&#8221;&gt;<br />
				&lt;cfreturn &#8220;This is the content returned from the CFC for<br />
					the div, the calling page variable is &#8216;&lt;strong&gt;#arguments.edit#&lt;/<br />
					strong&gt;&#8217;.&#8221;&gt;<br />
		&lt;/cffunction&gt;<br />
	&lt;/cfcomponent&gt;<br />
</CODE></PRE></P><br />
<P>From the previous code, we can see that the CFC only accepts the argument<br />
and passes it back. This could have even returned an image HTML segment<br />
with something like a user picture. The following code shows the new page<br />
code modifications.</P><br />
<P><PRE><CODE><br />
	&lt;cfform id=&#8221;myForm&#8221; format=&#8221;html&#8221;&gt;<br />
		This is my edit box.&lt;br /&gt;<br />
		&lt;cfinput type=&#8221;text&#8221; name=&#8221;myText&#8221;&gt;<br />
	&lt;/cfform&gt;<br />
	&lt;hr /&gt;<br />
	And this is the bound div container.&lt;br /&gt;<br />
	&lt;cfdiv bind=&#8221;cfc:bindsource.getDivContent({myText})&#8221;&gt;&lt;/cfdiv&gt;<br />
</CODE></PRE></P><br />
<P>The only change lies in how we bind the cfdiv element tag. Here, you can see that<br />
it starts with CFC. Next, it calls bindsource, which is the name of a local CFC. This<br />
tells ColdFusion to wire up the browser page, so it will connect to the CFC and<br />
things will work as we want. You can observe that inside the method, we are passing<br />
the bound variable to the method. When the input field changes by losing focus, the<br />
browser sends a new request to the CFC and updates the div. We need to have the<br />
same number of parameters going to the CFC as the number of arguments in our<br />
CFC method. We should also make sure that the method has its access method set to<br />
remote. Here we can see an example results page.</P></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><center><img src="images/2009/11/Ajax/2.jpg"/></center></p>
<p><P>It is valid to pass the name of the CFC method argument with the data value. This<br />
can prevent exceptions caused by not pairing the data in the same order as the<br />
method arguments. The last line of the previous code can be modified as follows:</P><br />
<P><PRE><CODE><br />
	<B>&lt;cfdiv bind=&#8221;cfc:bindsource.getDivContent(edit:{myText})&#8221;&gt;&lt;/cfdiv&gt;</B><br />
</CODE></PRE></P></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/11/cf-ajax-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yahoo! User Interface library(YUI)</title>
		<link>http://www.javabeat.net/2008/12/yahoo-user-interface-libraryyui/</link>
		<comments>http://www.javabeat.net/2008/12/yahoo-user-interface-libraryyui/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 16:00:08 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2239</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>About Yahoo! User Interface Library &#8211; Book Learning the Yahoo! User Interface Library introduces the popular open-source YUI JavaScript library and takes the user through each of the fully released components in detail looking at the classes that make up each component and the properties and methods that can be used. It includes a series [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>About Yahoo! User Interface Library &#8211; Book</h2>
<p>Learning the Yahoo! User Interface Library introduces the popular open-source <b><i>YUI</i></b> JavaScript library and takes the user through each of the fully released components in detail looking at the classes that make up each component and the properties and methods that can be used. It includes a series of practical examples to reinforce how each component should/can be used.  Author Dan Wellman takes the reader from beginner to advanced-level <b><i>YUI</i></b> usage and understanding.</p>
<h2>What This Book Covers</h2>
<p>
In Chapter 1 we look at the library as a whole covering subjects such as how it can be<br />
obtained, how it can be used, the structure and composition of it, and the license it has<br />
been released under. We also look at a coding example featuring the Calendar control.</p>
<p>Chapter 2 covers the extensive CSS tools that come with the library, specifically the<br />
Reset and Base tools, the Fonts tool, and the extremely capable Grids tool. Examples on<br />
the use of each tool are covered.</p>
<p>In Chapter 3 we look at the all important <b><i>DOM</i></b> and Event utilities. These two<br />
comprehensive utilities can often form the backbone of any modern web application and<br />
are described in detail. We look at the differences between traditional and <b><i>YUI</i></b> methods<br />
of <b><i>DOM</i></b> manipulation, and how the Event utility unites the conflicting Event models of<br />
different browsers. Examples in this chapter include how the basic functions of the <b><i>DOM</i></b><br />
utility are used, and how custom events can be defined and subscribed to.</p>
<p><b><i>AJAX</i></b> is the subject of Chapter 4, where we look in detail at how the Connection<br />
Manager handles all of our <b><i>XHR</i></b> requirements. Examples include obtaining remote<br />
data from external domains and the sending and receiving of data asynchronously to our<br />
own servers.</p>
<p>Chapter 5 looks first at how the Animation utility can be used to add professional effects<br />
to your web pages. It then moves on to cover how the Browser History Manager reenables<br />
the back and forward buttons and bookmarking functionality of the browser when<br />
used with dynamic web applications.</p>
<p>The Button family of controls and the TreeView control are the focus of Chapter 6. We<br />
first cover each of the different buttons and look at examples of their use. We then<br />
implement a TreeView control and investigate the methods and properties made available<br />
by its classes.</p>
<p>In Chapter 7 we look at one of the most common parts of any web site—the navigation<br />
structure. The example looks at the ease at which the Menu control can be implemented.<br />
We also look at the AutoComplete control and create both array and XHR-based versions<br />
of this component.</p>
<p>Chapter 8 looks at the container family of controls as well as the tabView control. Each<br />
member of the container family is investigated and implemented in the coding examples.<br />
The visually engaging and highly interactive TabView control is also looked at and<br />
implemented.</p>
<p>Drag-and-Drop, one of <b><i>DHTML</i></b>&#8216;s crowning acheivements is wrapped up in an easy to<br />
use utility, forms the first part of Chapter 9. In the second part of this chapter we look<br />
at the related Slider control and how this basic but useful control can be added to pages<br />
with ease.</p>
<p>In Chapter 10 we cover the Logger control in detail and work through several examples<br />
that include how the Logger is used to view the event execution of other controls and<br />
how it can be used to debug existing controls and custom classes.</p>
<h2><center><b><i>AJAX</i></b> and Connection Manager</center></h2>
<p>As far as web interface design techniques are concerned, <b><i>AJAX</i></b> is defi nitely the way to go. So what JavaScript library worth its salt these days wouldn&#8217;t want to include a component dedicated to this extremely useful and versatile method of client/server communication?</p>
<p>The term <b><i>AJAX</i></b> has been part of the mainstream development community&#8217;s vocabulary since early 2005 (with the advent of Google Mail). Although some of the key components that <b><i>AJAX</i></b> consists of, such as the XMLHttp object, have been around for much longer (almost a decade in fact). The goal of asynchronously loading additional data after a web page has rendered is also not a new concept or requirement.</p>
<p>Yet <b><i>AJAX</i></b> reinvented existing technologies as something new and exciting, and paved the way to a better, more attractive, and interactive web (sometimes referred to loosely as web 2.0) where web applications feel much more like desktop applications.</p>
<p><b><i>AJAX</i></b> can also perhaps be viewed as the godfather of many modern JavaScript libraries. Maybe it wasn&#8217;t the sole motivating factor behind the growing plethora of available libraries, but it was certainly highly infl uential and orchestral in their creation and was at least partly responsible for the fi rst wave of modern, class-based JavaScript libraries.</p>
<p>Like many other cornerstone web techniques developed over the years, <b><i>AJAX</i></b> was (and still is) implemented in entirely different ways by different browsers. I don&#8217;t know if developers just fi nally had enough of dealing with these issues.</p>
<p>The very fi rst JavaScript libraries sprang into existence as a means of abstracting away the differences in <b><i>AJAX</i></b> implementation between platforms, thereby allowing developers to focus on the important things in web design instead of worrying about compatibility issues.</p>
<p>The result in many cases is a quick and easy way for developers to cut down on the amount of code they are required to produce, and a better more interactive experience for end users and website visitors.</p>
<h2>The Connection Manager—A Special Introduction</h2>
<p>The Connection Manager utility is by no means the smallest, most light-weight component included with the <b><i>YUI</i></b>, but it&#8217;s certainly not the largest either, yet it packs so much functionality into just 12Kb (for the –min version).</p>
<p>Connection Manager provides a fast and reliable means of accessing server-side resources, such as <b><i>PHP</i></b> or ASP scripts and handling the response. A series of supporting objects manage the different stages of any asynchronous transactions, whilst providing additional functionality where necessary.</p>
<p>Connection is one of just a few of the utilities that are supported by a single class; this makes looking up its methods nice and straight-forward. It also doesn&#8217;t have any properties at all (although the objects that it creates all have their own members which hold various pieces of information), which makes using it even easier!</p>
<p>This utility is what is known as a singleton utility, which means that there can only be one live instance of the utility at any one time, differing from many of the other components of the library. Don&#8217;t worry though, this doesn&#8217;t restrict you to only making one request; Connection will manage as many separate requests as you need.</p>
<p>Because this utility is a singleton, there are important considerations that advanced coders may want to take note of. Unlike some of the other library components, Connection cannot be subclassed—all of its class&#8217;s members are static, meaning that they won&#8217;t be picked up when using the <b><i>YAHOO</i></b> global .extend() method.</p>
<p>It wraps up the cross-browser creation of the <b><i>XMLHttpRequest</i></b> (<b><i>XHR</i></b>) object, as well as a simple to use object-based method of accessing the server response and any associated data, into a simple package which handles the request from start to finish. This requires minimal input from you, the developer, saving time as well as effort.</p>
<p>Another object created by Connection is the response object, which is created once the transaction has completed. The response object gives you access via its members to a rich set of data including the id of the transaction, the HTTP status code and status message, and either the responseText and responseXML members depending on the format of the data returned.</p>
<p>Like most of the other library components, Connection Manager provides a series of global custom events that can be used to hook into key moments during any transaction. We&#8217;ll look at these events in more detail later on in the chapter but rest assured, there are events marking the start and completion of transactions, as well as success, failure, and abort events.</p>
<p>The Connection utility has been a part of the <b><i>YUI</i></b> since its second public release (the 0.9.0 release) and has seen considerable bug fi xing and refi nement since this time. This makes it one of the more reliable and better documented utilities available.</p>
<p>Connection is such a useful utility that it&#8217;s used by several other library components in order to obtain data from remote sources. Other components that make use of Connection Manager include the AutoComplete control, DataTable, DataSource, and Tabview.</p>
<p>It is one of the only library components not dependant on the <b><i>DOM</i></b> utility. All it requires are the <b><i>YAHOO</i></b> global utility and the Event utility. That doesn&#8217;t mean that you can&#8217;t include a reference to the <b><i>DOM</i></b> utility, however, to make use of its excellent <b><i>DOM</i></b> manipulation convenience methods.</p>
<h2>The <b><i>XMLHttpRequest</i></b> Object Interface</h2>
<p>When working with the Connection utility you&#8217;ll never be required to manually create or access an <b><i>XHR</i></b> object directly. Instead, you talk to the utility and this works with the object for you using whichever code is appropriate for the browser in use. This means that you don&#8217;t need separate methods of creating an <b><i>XHR</i></b> object in order to keep each browser happy.</p>
<p>A transaction describes the complete process of making a request to the server and receiving and processing the response. Connection Manager handles transactions from beginning to end, providing different services at different points during a request.</p>
<p>Transactions are initiated using the .asyncRequest() method which acts as a constructor for the connection object. The method takes several arguments: the fi rst specifi es the HTTP method that the transaction should use, the second specifi es the URL of your server-side script while the third allows you to add a reference to a callback object.</p>
<p>A fourth, optional, argument can also be used to specify a POST message if the HTTP method is set to use POST giving you an easy means of sending data to the server as well as retrieving it. This is rarely required however, even when using the POST method, as we shall see later in the chapter.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>It&#8217;s also very easy to build in query string parameters if these are required to obtain the data that you are making the request for. It can be hard coded into a variable and then passed in as the second argument of the Connection constructor instead of setting the second argument manually within the constructor.</p>
<p>Connection Manager takes these arguments and uses them to set up the <b><i>XHR</i></b> object that will be used for the transaction on your behalf. Once this has been done, and Connection has made the request, you then need to defi ne a new object yourself that will allow you to react to a range of responses from the server.</p>
<h2>A Closer Look at the Response Object</h2>
<p>I briefl y mentioned the response object that is created by the utility automatically once a transaction has completed, let&#8217;s now take a slightly more in-depth view at this object. It will be created after any transaction, whether or not it was considered a success.</p>
<p>The callback functions you defi ne to handle successful or failed transactions (which we&#8217;ll examine in more detail very shortly) are automatically passed to the response object as an argument. Accessing it is extremely easy and requires no additional intervention from yourself.</p>
<p>If the transaction fails, this object gives you access to the HTTP failure code and HTTP status message which are received from the server. Examining these two members of the response object can highlight what happened to make the request fail, making it integral to any Connection implementation.</p>
<p>If the transaction was a success, these two members will still be populated but with a success code and status message, and additional members such as responseText or responseXML will also contain data for you to manipulate.</p>
<p>If you need to obtain the HTTP response headers sent by the server as part of the response, these can be obtained using either the getResponseHeader collection, or the getAllResponseHeaders member.</p>
<p>In the case of fi le uploads, some of these members will not be available via the response object. File uploads are the one type of transaction that do not make use of the <b><i>XHR</i></b> object at all, so the HTTP code and status message members cannot be used. Similarly, there will not be either a textual or XML-based response when uploading files.</p>
<h2>Managing the Response with a Callback Object</h2>
<p>In order to successfully negotiate the response from the server, a literal callback object should be defi ned which allows you to deal quickly and easily with the information returned whether it is a success, failure, or another category of response.</p>
<p>Each member of this object invokes a callback function or performs some other action relevant to your implementation. These members can be one of several types including another object, a function call or even a string or integer depending on the requirements of your application.</p>
<p>The most common members you would use in your callback object would usually be based upon success and failure function calls to handle these basic response types, with each member calling its associated function when a particular HTTP response code is received by the response object.</p>
<p>It&#8217;s also very easy to add an additional member to this object which allows you to include data which may be useful when processing the response form the server. In this situation, the argument object member can be used and can take a string, a number, an object, or an array.</p>
<p>Other optional members include a customevents handler to deal with custom, pertransaction events as opposed to the global events that are available to any and all transactions, a scope object used to set the scope of your handler functions, and a timeout count used to set the wait time before Connection aborts the transaction and assumes failure.</p>
<p>The remaining member of the callback object is the upload handler which is of course a special handler to deal specifi cally with fi le uploads. As I already mentioned, the response object will be missing success of failure details when dealing with fi le uploads, however, you can still defi ne a callback function to be executed once the upload transaction has completed.</p>
<h2>Working with responseXML</h2>
<p>In this example we&#8217;re going to look at a common response type you may want to use—responseXML. We can build a simple news reader that reads headlines from a<br />
remote XML fi le and displays them on the page.</p>
<p>We&#8217;ll also need an intermediary <b><i>PHP</i></b> fi le that will actually retrieve the XML file from the remote server and pass it back to the Connection Manager. Because of the<br />
security restrictions placed upon all browsers we can&#8217;t use the <b><i>XHR</i></b> object to obtain the XML fi le directly because it resides on another domain.</p>
<p>This is not a problem for us however, because we can use the intermediary <b><i>PHP</i></b> fi le that we&#8217;re going to have to create anyway as a proxy. We&#8217;ll make requests from<br />
the browser to the proxy thereby sidestepping any security issues, and the proxy will then make requests to the external domain&#8217;s server. The proxy used here in<br />
this example is a cut down version of that created by Jason Levitt that I modified specifi cally for this example.</p>
<p>In order to complete this example you&#8217;ll need to use a full web server setup, with <b><i>PHP</i></b> installed and confi gured. Our proxy <b><i>PHP</i></b> fi le will also make use of the cURL<br />
library, so this will also need to be installed on your server.</p>
<p>The installation of cURL varies depending on the platform in use, so full instructions for installing it is beyond the scope of this book, but don&#8217;t worry because there are<br />
some excellent guides available online that explain this quick and simple procedure.</p>
<p>Even though Connection Manager only requires the <b><i>YAHOO</i></b> and Event utilities to function correctly, we can make use of some of the convenient functionality provided<br />
by the <b><i>DOM</i></b> utility, so we will use the aggregated yahoo-dom-event.js instead of the individual <b><i>YAHOO</i></b> and Event fi les. We&#8217;ll also need connection-min.js and<br />
fonts.css so make sure these are all present in your yui folder and begin with the following HTML:</p>
<p>
<pre><code>
	&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
	&lt;html lang="en"&gt;
	   &lt;head&gt;
		&lt;meta http-equiv="content-type" content="text/html; charset=utf-8"&gt;
		&lt;title&gt;Yui Connection Manager Example&lt;/title&gt;
		&lt;script type="text/javascript" src="images/2008/12/yahoo/yui/yahoo-dom-event.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript" src="images/2008/12/yahoo/yui/connection-min.js"&gt;&lt;/script&gt;
		&lt;link rel="stylesheet" type="text/css" href="yui/assets/fonts-min.css"&gt;
		&lt;link rel="stylesheet" type="text/css" href="responseXML.css"&gt;
	   &lt;/head&gt;
	   &lt;body&gt;
		&lt;div id="newsreader"&gt;
		   &lt;div class="header"&gt;Recent News&lt;/div&gt;
		   &lt;div id="newsitems"&gt;&lt;/div&gt;
		   &lt;div id="footer"&gt;&lt;a class="link" href="http://news.bbc.co.uk/1/hi/ help/rss/4498287.stm"&gt;
							Copyright: &copy; British
							Broadcasting Corporation&lt;/a&gt;&lt;/div&gt;
		&lt;div&gt;
	   &lt;/body&gt;
	&lt;/html&gt;
</code></pre>
</p>
<p>We&#8217;ll start off with this very simple page which at this stage contains just the markup for the newsreader and the references to the required library fi les. There&#8217;s also a &lt;link&gt; to a custom stylesheet which we&#8217;ll create in a little while.</p>
<h2>Adding the JavaScript</h2>
<p>Directly after the final closing &lt;/div&gt; tag, add the following &lt;script&gt;:&lt;/p&gt;</p>
<p>
<pre><code>
	&lt;script type="text/javascript"&gt;
	   //create namespace object for this example
	   <b><i>YAHOO</i></b>.namespace("yuibook.newsreader");
	   //define the initConnection function
	   <b><i>YAHOO</i></b>.yuibook.newsreader.initConnection = function() {
	     //define the <b><i>AJAX</i></b> success handler
	     var successHandler = function(o) {
		//define the arrays
		var titles = new Array();
		var descs = new Array();
		var links = new Array();

		//get a reference to the newsitems container
		var newsitems = document.getElementById("newsitems");

		//get the root of the XML doc
		var root = o.responseXML.documentElement;

		//get the elements from the doc we want
		var doctitles = root.getElementsByTagName("title");
		var docdescs = root.getElementsByTagName("description");
		var doclinks = root.getElementsByTagName("link");

		//map the collections into the arrays
		for (x = 0; x &lt; doctitles.length; x++){
		   titles[x] = doctitles[x];
		   descs[x] = docdescs[x];
		   links[x] = doclinks[x];
		}
		//removed the unwanted items from the arrays
		titles.reverse();
		titles.pop();
		titles.pop();
		titles.reverse();
		descs.reverse();
		descs.pop();
		descs.reverse();
		links.reverse();
		links.pop();
		links.pop();
		links.reverse();

		//present the data from the arrays
		for (x = 0; x &lt; 5; x++) {
		   //create new elements
		   var div = document.createElement("div");
		   var p1 = document.createElement("p");
		   var p2 = document.createElement("p");
		   var a = document.createElement("a");

		   //give classes to new elements for styling
		   <b><i>YAHOO</i></b>.util.Dom.addClass(p1, "title");
		   <b><i>YAHOO</i></b>.util.Dom.addClass(p2, "desc");
		   <b><i>YAHOO</i></b>.util.Dom.addClass(a, "newslink");

		   //create new text nodes and the link
		   var title = document.createTextNode(titles[x].firstChild.nodeValue);
		   var desc = document.createTextNode(descs[x].firstChild.nodeValue);
		   var link = links[x].firstChild.nodeValue;
		   a.setAttribute("href", link);

		   //add the new elements to the page
		   a.appendChild(desc);
		   p1.appendChild(title);
		   p2.appendChild(a);
		   div.appendChild(p1)
		   div.appendChild(p2)
		   newsitems.appendChild(div);
		}
	     }
	     //define the <b><i>AJAX</i></b> failure handler
	     var failureHandler = function(o) {
		//alert the status code and error text
		alert(o.status + " : " + o.statusText);
	     }
	     //define the callback object
	     var callback = {
		success:successHandler,
		failure:failureHandler
	     };
	     //initiate the transaction
	     var transaction = <b><i>YAHOO</i></b>.util.Connect.asyncRequest("GET", "myproxy.php", callback, null);
	   }
	   //execute initConnection when <b><i>DOM</i></b> is ready
	   <b><i>YAHOO</i></b>.util.Event.onDOMReady( <b><i>YAHOO</i></b>.yuibook.newsreader.initConnection);
	&lt;/script&gt;
</code></pre>
</p>
<p>Once again, we can make use of the .onDOMReady() method to specify a callback function that is to be executed when the <b><i>YUI</i></b> detects that the <b><i>DOM</i></b> is ready, which is usually as soon as the page has fi nished loading.</p>
<p>The code within our master initialization function is split into distinct sections. We have our success and failure callback functions, as well as a callback object which will call either the success or failure function depending on the HTTP status code received following the request.</p>
<p>The failure handler code is very short; we can simply alert the HTTP status code and status message to the visitor. The callback object, held in the variable callback, is equally as simple, just containing references to the success and failure functions as values.</p>
<p>The pseudo-constructor which sets up the actual request using the .asyncRequest() method is just a single line of code, It&#8217;s arguments specify the response method (GET), the name of the <b><i>PHP</i></b> fi le that will process our request (myproxy.php), the name of our callback object (callback), and a null reference.</p>
<p>Connection Manager is able to accept URL query string parameters that are passed to the server-side script. Any parameters are passed using the fourth argument of the .asyncRequest() method and as we don&#8217;t need this feature in this implementation, we can simply pass in null instead.</p>
<p>Most of our program logic resides in the successHandler() function. The response object (o) is automatically passed to our callback handlers (both success and failure) and can be received simply by including it between brackets in the function declaration. Let&#8217;s break down what each part of our successHandler() function does.</p>
<p>We fi rst defi ne three arrays; they need to be proper arrays so that some useful array methods can be called on the items we extract from the remote XML fi le. It does make the code bigger, but means that we can get exactly the data we need, in the format that we want. We also grab the newsitems container from the <b><i>DOM</i></b>.</p>
<p>The root variable that we declare next allows us easy access to the root of the XML document, which for reference is a news feed from the BBC presented in <b><i>RSS</i></b> 2.0 format. The three variables following root allow us to strip out all of the elements we are interested in.</p>
<p>These three variables will end up as collections of elements, which are similar to arrays in almost every way except that array methods, such as the ones we need to use, cannot be called on the</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/12/yahoo-user-interface-libraryyui/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DWR Java AJAX Applications</title>
		<link>http://www.javabeat.net/2008/12/dwr-java-ajax-applications/</link>
		<comments>http://www.javabeat.net/2008/12/dwr-java-ajax-applications/#comments</comments>
		<pubDate>Sat, 13 Dec 2008 16:08:31 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2254</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this chapter, we will get to the actual hands-on work. We will develop samples based on DWR, which show how to dynamically change the common user interface elements such as tables and lists as well as fi eld completion. We also make a dynamic user interface skeleton for our samples that will hold all the samples in [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><span style="font-size: 13px;">In this chapter, we will get to the actual hands-on work. We will develop samples </span>based on <b><i>DWR</i></b>, which show how to dynamically change the common user interface elements such as tables and lists as well as fi eld completion. We also make a dynamic user interface skeleton for our samples that will hold all the samples in this book.</p>
<p>The section on dynamic user interfaces shows how to get started with a <b><i>DWR </i></b>application, and it presents a user interface skeleton that will be used to hold the tables and lists sample, and the fi eld completion (aka. autosuggest/autocomplete) sample. Samples in the following chapter will use the same user interface skeleton, with the exception of the sample applications in Chapter 7.</p>
<p>The following are the sections in this chapter:</p>
<ul>
<li>Creating a <b>Dynamic User Interface</b>—starts with creating a web project and a<br />
basis for samples mentioned in this chapter</li>
<li>Implementing Tables and Lists—shows us how to use <b><i>DWR</i></b> with them</li>
<li>Implementing Field Completion—has a sample for typical fi eld completion</li>
</ul>
<h2>Creating a Dynamic User Interface</h2>
<p>The idea behind a <b>dynamic user interface</b> is to have a common &#8220;framework&#8221; for all samples. We will create a new web application and then add new features to the application as we go on. The user interface will look something like the following figure:</p>
<p>The user interface has three main areas: the title/logo that is static, the tabs that are dynamic, and the content area that shows the actual content.</p>
<p>The idea behind this implementation is to use <b><i>DWR</i></b> functionality to generate tabs and to get content for the tab pages. The tabbed user interface is created using a <b><i>CSS</i></b> template from the Dynamic Drive <b><i>CSS</i></b> Library (http://dynamicdrive.com/style/csslibrary/item/css-tabs-menu). Tabs are read from a properties fi le, so it is possible to dynamically add new tabs to the web page. The following screenshot shows the user interface.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-1.gif"><img class="aligncenter size-full wp-image-6904" alt="dwr-1" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-1.gif" width="499" height="86" /></a></p>
<h2>Creating a New Web Project</h2>
<ul>
<li>1.First, we will create a new web project. Using the <b><i>Eclipse</i></b> IDE we do the following: select the menu File | New | Dynamic Web Project.</li>
<li>2.This opens the New Dynamic Web Project dialog; enter the project name <b><i>DWR</i></b>EasyAjax and click Next, and accept the defaults on all the pages till the last page, where Geronimo Deployment Plan is created as shown in the following screenshot:</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-2.gif"><img class="aligncenter  wp-image-6905" alt="dwr-2" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-2.gif" width="432" height="194" /></a></li>
<li>3.Enter easyajax as Group Id and <b><i>DWR</i></b>EasyAjax as Artifact Id. On clicking Finish, <b><i>Eclipse</i></b> creates a new web project. The following screen shot shows the generated project and the directory hierarchy.</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-3.gif"><img class="aligncenter size-full wp-image-6906" alt="dwr-3" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-3.gif" width="234" height="342" /></a></li>
<li>4.Before starting to do anything else, we need to copy <b><i>DWR</i></b> to our web application. All <b><i>DWR</i></b> functionality is present in the dwr.jar fi le, and we just copy that to the WEB-INF | lib directory.</li>
</ul>
<p>A couple of files are noteworthy: web.xml and <b>geronimo-web.xml</b>. The latter is generated for the Geronimo application server, and we can leave it as it is. <b><i>Eclipse </i></b>has an editor to show the contents of <b>geronimo-web.xml</b> when we double-clickthe file.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-4.gif"><img class="aligncenter size-full wp-image-6907" alt="dwr-4" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-4.gif" width="368" height="291" /></a></p>
<h2>Configuring the Web Application</h2>
<p>The context root is worth noting (visible in the screenshot above). We will need it when we test the application.</p>
<p>The other XML fi le, web.xml, is very important as we all know. This XML will hold the <b><i>DWR</i></b> servlet defi nition and other possible initialization parameters. The following code shows the full contents of the web.xml file that we will use:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.
sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
&lt;display-name&gt;&lt;b&gt;&lt;i&gt;DWR&lt;/i&gt;&lt;/b&gt;EasyAjax&lt;/display-name&gt;
&lt;servlet&gt;
&lt;display-name&gt;&lt;b&gt;&lt;i&gt;DWR&lt;/i&gt;&lt;/b&gt; Servlet&lt;/display-name&gt;
&lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;
&lt;servlet-class&gt;
org.directwebremoting.servlet.DwrServlet
&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;debug&lt;/param-name&gt;
&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;
&lt;url-pattern&gt;/dwr/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;welcome-file-list&gt;
&lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
&lt;welcome-file&gt;index.htm&lt;/welcome-file&gt;
&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
&lt;welcome-file&gt;default.html&lt;/welcome-file&gt;
&lt;welcome-file&gt;default.htm&lt;/welcome-file&gt;
&lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt;
&lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>
<p>We hav e already seen the servlet defi nition in Chapter 3, in the section on confi guration. We use the same debug-init parameter here. Servlet mapping is the commonly used /dwr/*.</p>
<p>We remember that <b><i>DWR</i></b> cannot function without the <b><i>dwr.xml</i></b> configuration file. So we need to create the confi guration fi le. We use <b><i>Eclipse</i></b> to create a new XML file in the WEB-INF directory. The following is required for the user interface skeleton. It already includes the allow-element for our <b><i>DWR</i></b> based menu.</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE dwr PUBLIC
&quot;-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN&quot;
&quot;http://getahead.org/dwr/dwr20.dtd&quot;&gt;
&lt;dwr&gt;
&lt;allow&gt;
&lt;create creator=&quot;new&quot; javascript=&quot;HorizontalMenu&quot;&gt;
&lt;param name=&quot;class&quot; value=&quot;samples.HorizontalMenu&quot; /&gt;
&lt;/create&gt;
&lt;/allow&gt;
&lt;/dwr&gt;
</pre>
<p>In the allow element, there is a creator for the horizontal menu Java class that we are going to implement here. The creator that we use here is the new creator, which means that <b><i>DWR</i></b> will use an empty constructor to create Java objects for clients. The parameter named class holds the fully qualifi ed class name.</p>
<h2>Developing the Web Application</h2>
<p>Since we have already defi ned the name of the Java class that will be used for creating the menu, the next thing we do is implement it. The idea behind the HorizontalMenu class is that it is used to read a properties fi le that holds the menus that are going to be on the web page.</p>
<p>We add properties to a fi le named dwrapplication.properties, and we create it in the same samples-package as the HorizontalMenu-class. The properties fi le for the menu items is as follows:</p>
<p>menu.1=Tables and lists,TablesAndLists<br />
menu.2=Field completion,FieldCompletion</p>
<p>The syntax for the menu property is that it contains two elements separated by a comma. The fi rst element is the name of the menu item. This is visible to user. The second is the name of HTML template fi le that will hold the page content of the menu item. The class contains just one method, which is used from JavaScript and via <b><i>DWR</i></b> to retrieve the menu items. The full class implementation is shown here:</p>
<pre class="brush: java; title: ; notranslate">
package samples;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
public class HorizontalMenu {
public HorizontalMenu() {
}
public List&lt;String&gt; getMenuItems() throws IOException {
List&lt;String&gt; menuItems = new Vector&lt;String&gt;();
InputStream is = this.getClass().getClassLoader().
getResourceAsStream(
&quot;samples/dwrapplication.properties&quot;);
Properties appProps = new Properties();
appProps.load(is);
is.close();
for (int menuCount = 1; true; menuCount++) {
String menuItem = appProps.getProperty(&quot;menu.&quot; + menuCount);
if (menuItem == null) {
break;
}
menuItems.add(menuItem);
}
return menuItems;
}
}
</pre>
<p>The implementation is straightforward. The getMenuItems() method loads properties using the ClassLoader.getResourceAsStream() method, which searches the class path for the specified resource. Then, after loading properties, a for loop is used to loop through menu items and then a List of String-objects is returned to the client. The client is the JavaScript callback function that we will see later. <b><i>DWR </i></b>automatically converts the List of String objects to JavaScript arrays, so we don&#8217;t have to worry about that.</p>
<h2>Testing the Web Application</h2>
<p>We hav en&#8217;t completed any client-side code now, but let&#8217;s test the code anyway. Testing uses the Geronimo test environment.</p>
<p>1.The Project context menu has the Run As menu that we use to test the application as shown in the following screenshot:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-5.gif"><img class="aligncenter  wp-image-6908" alt="dwr-5" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-5.gif" width="430" height="383" /></a></p>
<p>2.Run on Server opens a wizard to defi ne a new server runtime. The following screenshot shows that the Geronimo test environment has already been set up, and we just click Finish to run the application. If the test environment is not set up, we can manually defi ne a new one in this dialog:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-6.gif"><img class="aligncenter  wp-image-6909" alt="dwr-6" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-6.gif" width="447" height="380" /></a></p>
<p>3.After we click Finish, <b><i>Eclipse</i></b> starts the Geronimo test environment and our application with it. When the server starts, the Console tab in <b><i>Eclipse</i></b> informs us that it&#8217;s been started.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-7.gif"><img class="aligncenter  wp-image-6910" alt="dwr-7" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-7.gif" width="454" height="86" /></a></p>
<p>The Servers tab shows that the server is started and all the code has been synchronized, that is, the code is the most recent (Synchronization happens whenever we save changes on some deployed fi le.) The Servers tab also has a list of deployed applications under the server. Just the one application that we are testing here is visible in the Servers tab.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-8.gif"><img class="aligncenter  wp-image-6911" alt="dwr-8" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-8.gif" width="454" height="86" /></a></p>
<p>Now comes the interesting part—what are we going to test if we haven&#8217;t really implemented anything? If we take a look at the web.xml fi le, we will fi nd that we have defi ned one initialization parameter. The Debug parameter is true, which means that <b><i>DWR</i></b> generates test pages for our remoted Java classes. We just point the browser (Firefox in our case) to the URL  ttp://127.0.0.1:8080/<b><i>DWR</i></b>EasyAjax/<br />
dwr and the following page opens up:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-9.gif"><img class="aligncenter  wp-image-6912" alt="dwr-9" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-9.gif" width="430" height="104" /></a></p>
<p>This page w ill show a list of all the classes that we allow to be remoted. When we click the class name, a test page opens as in the following screenshot:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-10.gif"><img class="aligncenter  wp-image-6913" alt="dwr-10" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-10.gif" width="478" height="359" /></a></p>
<p>This is an interesting page. We see all the allowed methods, in this case, all public class methods since we didn&#8217;t specifi cally include or exclude anything. The most important ones are the script elements, which we need to include in our HTML pages. <b><i>DWR</i></b> does not automatically know what we want in our web pages, so we must add the script includes in each page where we are using <b><i>DWR</i></b> and a<br />
remoted functionality.</p>
<p>Then there is the possibility of testing remoted methods. When we test our own method, getMenuItems(), we see a response in an alert box:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-11.gif"><img class="aligncenter size-full wp-image-6914" alt="dwr-11" src="http://www.javabeat.net/wp-content/uploads/2008/12/dwr-11.gif" width="325" height="141" /></a></p>
<p>The array in the alert box in the screenshot is the JavaScript array that <b><i>DWR</i></b> returns from our method.</p>
<h2>Developing Web Pages</h2>
<p>The next step is to add the web pages. Note that we can leave the test environment running. Whenever we change the application code, it is automatically published to test the environment, so we don&#8217;t need to stop and start the server each time we make some changes and want to test the application.</p>
<p>The CSS style sheet is from the Dynamic Drive CSS Library. The fi le is named styles.css, and it is in the WebContent directory in Eclipse IDE. The CSS code is as shown:</p>
<pre class="brush: java; title: ; notranslate">
/*URL: http://www.dynamicdrive.com/style/ */
.basictab{
padding: 3px 0;
margin-left: 0;
font: bold 12px Verdana;
border-bottom: 1px solid gray;
list-style-type: none;
text-align: left; /*set to left, center, or right to align the menu as
desired*/
}
.basictab li{
display: inline;
margin: 0;
}
.basictab li a{
text-decoration: none;
padding: 3px 7px;
margin-right: 3px;
border: 1px solid gray;
border-bottom: none;
background-color: #f6ffd5;
color: #2d2b2b;
}
.basictab li a:visited{
color: #2d2b2b;
}
.basictab li a:hover{
background-color: #DBFF6C;
color: black;
}
.basictab li a:active{
color: black;
}
.basictab li.selected a{ /*selected tab effect*/
position: relative;
top: 1px;
padding-top: 4px;
background-color: #DBFF6C;
color: black;
}
</pre>
<p>This CSS is shown for the sake of completion, and we will not go into details of CSS style sheets. It is suffi cient to say that CSS provides an excellent method to create websites with good presentation.</p>
<p><em id="__mceDel"><em id="__mceDel">The next step is the actual web page. We create an index.jsp page, in the WebContent directory, which will have the menu and also the JavaScript functions for our samples. It should be noted that although all JavaScript code is added to a single JSP page here in this sample, in &#8220;real&#8221; projects it would probably be more useful to create a separate fi le for JavaScript functions and include the JavaScript fi le in the HTML/JSP page using a code snippet such as this:<br />
<script type="text/javascript" src="myjavascriptcode/ HorizontalMenu.js">// <![CDATA[
.</p>
<p>We will add JavaScript functions later for each sample. The following is the JSP code
that shows the menu using the remoted HorizontalMenu class.</p>
<pre class="brush: java; title: ; notranslate">
&lt;%@ page lan guage=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-
1&quot;&gt;
&lt;link href=&quot;styles.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&gt;
&lt;script type='text/javascript' src='/DWREasyAjax/dwr/engine.js'&gt;&lt;/
script&gt;
&lt;script type='text/javascript' src='/DWREasyAjax/dwr/util.js'&gt;&lt;/
script&gt;
&lt;script type='text/javascript' src='/DWREasyAjax/dwr/interface/
HorizontalMenu.js'&gt;&lt;/script&gt;
&lt;title&gt;DWR samples&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function loadMenuItems()
{
HorizontalMenu.getMenuItems(setMenuItems);
}
function getContent(contentId)
{
AppContent.getContent(contentId,setContent);
}
function menuItemFormatter(item)
{
elements=item.split(',');
return '&lt;li&gt;&lt;a href=&quot;#&quot; onclick=&quot;getContent(\''+elements[1]+'\
');return false;&quot;&gt;'+elements[0]+'&lt;/a&gt;&lt;/li&gt;';
}
function setMenuItems(menuItems)
{
menu=dwr.util.byId(&quot;dwrMenu&quot;);
menuItemsHtml='';
for(var i=0;i&lt;menuItems.length;i++)
{
menuItemsHtml=menuItemsHtml+menuItemFormatter(menuItems[i]);
}
menu.innerHTML=menuItemsHtml;
}
function setContent(htmlArray)
{
var contentFunctions='';
var scriptToBeEvaled='';
var contentHtml='';
for(var i=0;i&lt;htmlArray.length;i++)
{
var html=htmlArray[i];
if(html.toLowerCase().indexOf('&lt;script')&gt;-1)
{
if(html.indexOf('TO BE EVALED')&gt;-1)
{
scriptToBeEvaled=html.substring(html.indexOf('&gt;')+1,
html.indexOf('&lt;/'));
}
else
{
eval(html.substring(html.indexOf('&gt;')+1,html.indexOf('&lt;/')));
contentFunctions+=html;
}
}
else
{
contentHtml+=html;
}
}
conte ntScriptArea=dwr.util.byId(&quot;contentAreaFunctions&quot;);
contentScriptArea.innerHTML=contentFunctions;
contentArea=dwr.util.byId(&quot;contentArea&quot;);
contentArea.innerHTML=contentHtml;
if(scriptToBeEvaled!='')
{
eval(scriptToBeEvaled);
}
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload=&quot;loadMenuItems()&quot;&gt;
&lt;h1&gt;DWR Easy Java Ajax Applications&lt;/h1&gt;
&lt;ul class=&quot;basictab&quot; id=&quot;dwrMenu&quot;&gt;
&lt;/ul&gt;
&lt;div id=&quot;contentAreaFunctions&quot;&gt;
&lt;/div&gt;
&lt;div id=&quot;contentArea&quot;&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This JSP is our user interface. The HTML is just normal HTML with a head element
and a body element. The head includes reference to a style sheet and to DWR
JavaScript fi les, engine.js, util.js, and our own HorizontalMenu.js. The util.
js fi le is optional, but as it contains very useful functions, it could be included in all
the web pages where we use the functions in util.js.</p>
<p>The body elem ent has a contentArea place holder for the content pages just
below the menu. It also contains the content area for JavaScript functions for a
particular content.The body element onload-event executes the loadMenuItems()
function when the page is loaded. The loadMenuItems()function calls the remoted
method of the HorizontalMenu Java class. The parameter of the HorizontalMenu.
getMenuItems()JavaScript function is the callback function that is called by DWR
when the Java method has been executed and it returns menu items.</p>
<p>The setMenuItems()function is a callback function for the loadMenuItems()
function mentioned in the previous paragraph. While loading menu items, the
Horizontal.getMenuItems()remoted method returns menu items as a List of
Strings as a parameter to the setMenuItems() function. The menu items are
formatted using the menuItemFormatter() helper function.</p>
<p>The menuItemFormatter()function creates li elements of menu texts. Menus are
formatted as links, (a href) and they have an onclick event that has a function call to
the getContent-function, which in turn calls the AppContent.getContent() function.
The AppContent is a remoted Java class, which we haven't implemented yet, and
its purpose is to read the HTML from a fi le based on the menu item that the user
clicked. Implementation of AppContent and the content pages are described in the
next section.</p>
<p>The setContent() function sets the HTML content to the content area and also
evaluates JavaScript options that are within the content to be inserted in the content
area (this is not used very much, but it is there for those who need it).</p>
<p>Our dynamic user interface looks like this:</p>
<p><img alt="" src="images/2008/12/12.GIF" /></p>
<p>Note the Fireb ug window at the bottom of the browser screen. The Firebug console
in the screenshot shows one POST request to our HorizontalMenu.getMenuItems()
method. Other Firebug features are extremely useful during development work, and
we fi nd it useful that Firebug has been enabled throughout the development work.</p>
<h2>Callback Functions</h2>
<p>We saw our fi r st callback function as a parameter in the HorizontalMenu.getMen
uItems(setMenuItems) function, and since callbacks are an important concept in
DWR, it would be good to discuss a little more about them now that we have seen
their fi rst usage.</p>
<p>Callbacks are used to operate on the data that was returned from a remoted method.
As DWR and AJAX are asynchronous, typical return values in RPCs (Remote
Procedure Calls), as in Java calls, do not work. DWR hides the details of calling the
callback functions and handles everything internally from the moment we return a
value from the remoted Java method to receiving the returned value to the
callback function.</p>
<p>Two methods are recommended while using callback functions.</p>
<p>We have already seen the fi rst method in the HorizontalMenu.getMenuItems
(setMenuItems) function call. Remember that there are no parameters in the
getMenuItems()Java method, but in the JavaScript call, we added the callback
function name at the end of the parameter list. If the Java method has parameters,
then the JavaScript call is similar to CountryDB.getCountries(selectedLett
ers,setCountryRows), where selectedLetters is the input parameter for the
Java method and setCountryRows is the name of the callback function (we see the
implementation later on).</p>
<p>The second method to use callbacks is a meta-data object in the remote JavaScript
call. An example (a full implementation is shown later in this chapter) is shown here:</p>
<pre class="brush: java; title: ; notranslate">
CountryDB.saveCountryNotes(ccode,newNotes, {
callback:function(newNotes)
{
//function body here
}
});
</pre>
<p>Here, the function is anonymous and its implementation is included in the JavaScript
call to the remoted Java method. One advantage here is that it is easy to read the
code, and the the code is executed immediately after we get the return value from the
Java method. The other advantage is that we can add extra options to the call.
Extra options include timeout and error handler as shown in the following example:</p>
<pre class="brush: java; title: ; notranslate">
CountryDB.saveCountryNotes(ccode,newNotes, {
callback:function(newNotes)
{
//function body here
},
timeout:10000,
errorHandler:function(errorMsg) { alert(errorMsg);}
});
</pre>
<p>It is also possible to add a callback function to those Java methods that do not return
a value. Adding a callback to methods with no return values would be useful in
getting a notifi cation when a remote call has been completed.</p>
<h2>Afterword</h2>
<p>Our first sample is ready, and it is also the basis for the following samples. We also
looked at how applications are tested in the Eclipse environment.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Using DWR, we can look at JavaScript code on the browser and Java code on the
server as one. It may take a while to get used to it, but it will change the way we
develop web applications. Logically, there is no longer a client and a server but just
a single run time platform that happens to be physically separate. But in practice, of
course, applications using DWR, JavaScript on the client and Java in the server, are
using the typical client-server interaction. This should be remembered when writing
applications in the logically single run-time platform.</p>
<h2>Implementing Tables and Lists</h2>
<p>The first actual sample is very common in applications: tables and lists. In this
sample, the table is populated using the DWR utility functions, and a remoted Java
class. The sample code also shows how DWR is used to do inline table editing. When
a table cell is double-clicked, an edit box opens, and it is used to save new cell data.
The sample will have country data in a CSV fi le: country Name, Long Name,
two-letter Code, Capital, and user-defi ned Notes. The user interface for the table
sample appears as shown in the following screenshot:</p>
<p><img alt="" src="images/2008/12/13.GIF" /></p>
<h2>Server Code for Tables and Lists</h2>
<p>T he fi rst thing to do is to get the country data. Country data is in a CSV fi le (named
countries.csv and located in the samples Java package). The following is an
excerpt of the content of the CSV fi le (data is from http://www.state.gov ).</p>
<pre class="brush: java; title: ; notranslate">
Short-form name,Long-form name,FIPS Code,Capital
Afghanistan,Islamic Republic of Afghanistan,AF,Kabul
Albania,Republic of Albania,AL,Tirana
Algeria,People's Democratic Republic of Algeria,AG,Algiers
Andorra,Principality of Andorra,AN,Andorra la Vella
Angola,Republic of Angola,AO,Luanda
Antigua and Barbuda,(no long-form name),AC,Saint John's
Argentina,Argentine Republic,AR,Buenos Aires
Armenia,Republic of Armenia,AM,Yerevan
</pre>
<p>The CSV fi le is read each time a client requests country data. Although this is not
very effi cient, it is good enough here. Other alternatives include an in-memory
cache or a real database such as Apache Derby or IBM DB2. As an example, we have
created a CountryDB class that is used to read and write the country CSV. We also
have another class, DBUtils, which has some helper methods. The DBUtils code is
as follows:</p>
<pre class="brush: java; title: ; notranslate">
package samples;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;
public class DBUtils {
private String fileName=null;
public void initFileDB(String fileName)
{
this.fileName=fileName;
// copy csv file to bin-directory, for easy
// file access
File countriesFile = new File(fileName);
if (!countriesFile.exists()) {
try {
List&lt;String&gt; countries = getCSVStrings(null);
PrintWriter pw;
pw = new PrintWriter(new FileWriter(countriesFile));
for (String country : countries) {
pw.println(country);
}
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
protected List&lt;String&gt; getCSVStrings(String letter) {
List&lt;String&gt; csvData = new Vector&lt;String&gt;();
try {
File csvFile = new File(fileName);
BufferedReader br = null;
if(csvFile.exists())
{
br=new BufferedReader(new FileReader(csvFile));
}
else
{
InputStream is = this.getClass().getClassLoader()
.getResourceAsStream(&quot;samples/&quot;+fileName);
br=new BufferedReader(new InputStreamReader(is));
br.readLine();
}
for (String line = br.readLine(); line != null; line =
br.readLine()) {
if (letter == null|| (letter != null &amp;amp;&amp;amp; line.startsWith(letter))) {
csvData.add(line);
}
}
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return csvData;
}
}
</pre>
<p>The DBUtils class is a straightforward utility class that returns CSV content as a
List of Strings. It also copies the original CSV fi le to the runtime directory of any
application server we might be running. This may not be the best practice, but it
makes it easier to manipulate the CSV fi le, and we always have the original CSV fi le
untouched if and when we need to go back to the original version.
The code for CountryDB is given here:</p>
<pre class="brush: java; title: ; notranslate">
package samples;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
public class CountryDB {
private DBUtils dbUtils = new DBUtils();
private String fileName = &quot;countries.csv&quot;;
public CountryDB() {
dbUtils.initFileDB(fileName);
}
public String[] getCountryData(String ccode) {
List&lt;String&gt; countries = dbUtils.getCSVStrings(null);
for (String country : countries) {
if (country.indexOf(&quot;,&quot; + ccode + &quot;,&quot;) &gt; -1) {
return country.split(&quot;,&quot;);
}
}
return new String[0];
}
public List&lt;List&lt;String&gt;&gt; getCountries(String startLetter) {
List&lt;List&lt;String&gt;&gt; allCountryData = new Vector&lt;List&lt;String&gt;&gt;();
List&lt;String&gt; countryData = dbUtils.getCSVStrings(startLetter);
for (String country : countryData) {
String[] data = country.split(&quot;,&quot;);
allCountryData.add(Arrays.asList(data));
}
return allCountryData;
}
public String[] saveCountryNotes(String ccode, String notes) {
List&lt;String&gt; countries = dbUtils.getCSVStrings(null);
try {
PrintWriter pw = new PrintWriter(new FileWriter(fileName));
for (String country : countries) {
if (country.indexOf(&quot;,&quot; + ccode + &quot;,&quot;) &gt; -1) {
if (country.split(&quot;,&quot;).length == 4) {
// no existing notes
country = country + &quot;,&quot; + notes;
} else {
if (notes.length() == 0) {
country = country.substring(0, country
.lastIndexOf(&quot;,&quot;));
} else {
country = country.substring(0, country
.lastIndexOf(&quot;,&quot;))
+ &quot;,&quot; + notes;
}
}
}
pw.println(country);
}
pw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
String[] rv = new String[2];
rv[0] = ccode;
rv[1] = notes;
return rv;
}
}
</pre>
<p>The CountryDB class is a remoted class. The getCountryData() method
returns country data as an array of strings based on the country code. The
getCountries()method returns all the countries that start with the specifi ed
parameter, and saveCountryNotes() saves user added notes to the country
specifi ed by the country code.</p>
<p>In order to use CountryDB, the following script element must be added to the
index.jsp fi le together with other JavaScript elements.</p>
<pre class="brush: java; title: ; notranslate">
&lt;script type='text/javascript' src='/DWREasyAjax/dwr/interface/
CountryDB.js'&gt;&lt;/script&gt;
</pre>
<p>There is one other Java class that we need to create and remote. That is the
AppContent class that was already present in the JavaScript functions of the home
page. The AppContent class is responsible for reading the content of the HTML fi le
and parses the possible JavaScript function out of it, so it can become usable by the
existing JavaScript functions in index.jsp file.</p>
<pre class="brush: java; title: ; notranslate">
package samples;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Vector;
public class AppContent {
public AppContent()
{
}
public List&lt;String&gt; getContent(String contentId)
{
InputStream is = this.getClass().getClassLoader().
getResourceAsStream(
&quot;samples/&quot;+contentId+&quot;.html&quot;);
String content=streamToString(is);
List&lt;String&gt; contentList=new Vector&lt;String&gt;();
//Javascript within script tag will be extracted and sent
separately to client
for(String script=getScript(content);!script.equals(&quot;&quot;);script=g
etScript(content))
{
contentList.add(script);
content=removeScript(content);
}
//content list will have all the javascript
//functions, last element is executed last
//and all other before html content
if(contentList.size()&gt;1)
{
contentList.add(contentList.size()-1, content);
}
else
{
contentList.add(content);
}
return contentList;
}
public List&lt;String&gt; getLetters()
{
List&lt;String&gt; letters=new Vector&lt;String&gt;();
char[] l=new char[1];
for(int i=65;i&lt;91;i++)
{
l[0]=(char)i;
letters.add(new String(l));
}
return letters;
}
public String removeScript(String html)
{
//removes first script element
int sIndex=html.toLowerCase().indexOf(&quot;&lt;script &quot;);
if(sIndex==-1)
{
return html;
}
int eIndex=html.toLowerCase().indexOf(&quot;&lt;/script&gt;&quot;)+9;
return html.substring(0, sIndex)+html.substring(eIndex);
}
public String getScript(String html)
{
//returns first script element
int sIndex=html.toLowerCase().indexOf(&quot;&lt;script &quot;);
if(sIndex==-1)
{
return &quot;&quot;;
}
int eIndex=html.toLowerCase().indexOf(&quot;&lt;/script&gt;&quot;)+9;
return html.substring(sIndex, eIndex);
}
public String streamToString(InputStream is)
{
String content=&quot;&quot;;
try
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
for(int b=is.read();b!=-1;b=is.read())
{
baos.write(b);
}
content=baos.toString();
}
catch(IOException ioe)
{
content=ioe.toString();
}
return content;
}
}
</pre>
<p>The getContent() method reads the HTML code from a fi le based on the
contentId. ContentId was specifi ed in the dwrapplication.properties fi le, and
the HTML is just contentId plus the extension .html in the package directory.
There is also a getLetters() method that simply lists letters from A to Z and
returns a list of letters to the browser.</p>
<p>If we test the application now, we will get an error as shown in the
following screenshot:</p>
<p><img alt="" src="images/2008/12/14.GIF" /></p>
<p>We know why the AppContent is not defi ned error occurs, so lets fi x it by adding
AppContent to the allow element in the dwr.xml fi le. We also add CountryDB to the
allow element. The fi rst thing we do is to add required elements to the dwr.xml fi le.
We add the following creators within the allow element in the dwr.xml fi le.</p>
<pre class="brush: java; title: ; notranslate">
&lt;create creator=&quot;new&quot; javascript=&quot;AppContent&quot;&gt;
&lt;param name=&quot;class&quot; value=&quot;samples.AppContent&quot; /&gt;
&lt;include method=&quot;getContent&quot; /&gt;
&lt;include method=&quot;getLetters&quot; /&gt;
&lt;/create&gt;
&lt;create creator=&quot;new&quot; javascript=&quot;CountryDB&quot;&gt;
&lt;param name=&quot;class&quot; value=&quot;samples.CountryDB&quot; /&gt;
&lt;include method=&quot;getCountries&quot; /&gt;
&lt;include method=&quot;saveCountryNotes&quot; /&gt;
&lt;include method=&quot;getCountryData&quot; /&gt;
&lt;/create&gt;
</pre>
<p>We explicitly define the methods we are remoting using the include elements. This
is a good practice, as we don't accidentally allow access to any methods that are not
meant to be remoted.</p>
<h2>Client Code for Tables and Lists</h2>
<p>We also need to add a JavaScript interface to the index.jsp page. Add the following
with the rest of the scripts in the index.jsp file.</p>
<pre class="brush: java; title: ; notranslate">
&lt;script type='text/javascript' src='/DWREasyAjax/dwr/interface/
AppContent.js'&gt;&lt;/script&gt;</pre>
<p>Be fore testing, we need the sample HTML for the content area. The following HTML
is in the TablesAndLists.html fi le under the samples directory:</p>
<pre class="brush: java; title: ; notranslate">
&lt;h3&gt;Countries&lt;/h3&gt;
&lt;p&gt;Show countries starting with
&lt;select id=&quot;letters&quot; onchange=&quot;selectLetter(this);return false;&quot;&gt; &lt;/
select&gt;&lt;br/&gt;
Doubleclick &quot;Notes&quot;-cell to add notes to country.
&lt;/p&gt;
&lt;table border=&quot;1&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;Long name&lt;/th&gt;
&lt;th&gt;Code&lt;/th&gt;
&lt;th&gt;Capital&lt;/th&gt;
&lt;th&gt;Notes&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody id=&quot;countryData&quot;&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;script type='text/javascript'&gt;
//TO BE EVALED
AppContent.getLetters(addLetters);
&lt;/script&gt;
</pre>
<p>The script element at the end is extracted by our Java class, and it is then evaluated
by the browser when the client-side JavaScript receives the HTML. There is the
select element, and its onchange event calls the selectLetter()JavaScript
function. We will implement the selectLetter() function shortly.</p>
<p>JavaScript functions are added in the index.jsp fi le, and within the head element.
Functions could be in separate JavaScript fi les, but the embedded script is just
fine here.</p>
<pre class="brush: java; title: ; notranslate">
function selectLetter(selectElement)
{
var selectedIndex = selectElement.selectedIndex;
var selectedLetter= selectElement.options[selectedIndex ].value;
CountryDB.getCountries(selectedLetter,setCountryRows);
}
function addLetters(letters)
{
dwr.util.addOptions('letters',['letter...']);
dwr.util.addOptions('letters',letters);
}
function setCountryRows(countryData)
{
var cellFuncs = [
function(data) { return data[0]; },
function(data) { return data[1]; },
function(data) { return data[2]; },
function(data) { return data[3]; },
function(data) { return data[4]; }
];
dwr.util.removeAllRows('countryData');
dwr.util.addRows( 'countryData',countryData,cellFuncs, {
cellCreator:function(options) {
var td = document.createElement(&quot;td&quot;);
if(options.cellNum==4)
{
var notes=options.rowData[4];
if(notes==undefined)
{
notes=' ';// + options.rowData[2]+'notes';
}
var ccode=options.rowData[2];
var divId=ccode+'_Notes';
var tdId=divId+'Cell';
td.setAttribute('id',tdId);
var html=getNotesHtml(ccode,notes);
td.innerHTML=html;
options.data=html;
}
return td;
},
escapeHtml:false
});
}
function getNotesHtml(ccode,notes)
{
var divId=ccode+'_Notes';
return &quot;&lt;div onDblClick=
\&quot;editCountryNotes('&quot;+divId+&quot;','&quot;+ccode+&quot;');\&quot; id=
\&quot;&quot;+divId+&quot;\&quot;&gt;&quot;+notes+&quot;&lt;/div&gt;&quot;;
}
function editCountryNotes(id,ccode)
{
var notesElement=dwr.util.byId(id);
var tdId=id+'Cell';
var notes=notesElement.innerHTML;
if(notes==' ')
{
notes='';
}
var editBox='&lt;input id=&quot;'+ccode+'NotesEditBox&quot; type=
&quot;text&quot; value=&quot;'+notes+'&quot;/&gt;&lt;br/&gt;';
editBox+=&quot;&lt;input type='button' id='&quot;+ccode+&quot;SaveNotesButton'
value='Save' onclick='saveCountryNotes(\&quot;&quot;+ccode+&quot;\&quot;);'/&gt;&quot;;
editBox+=&quot;&lt;input type='button' id='&quot;+ccode+&quot;CancelNotesButton'
value='Cancel' onclick='cancelEditNotes
(\&quot;&quot;+ccode+&quot;\&quot;);'/&gt;&quot;;
tdElement=dwr.util.byId(tdId);
tdElement.innerHTML=editBox;
dwr.util.byId(ccode+'NotesEditBox').focus();
}
function cancelEditNotes(ccode)
{
var countryData=CountryDB.getCountryData(ccode, {
callback:function(data)
{
var notes=data[4];
if(notes==undefined)
{
notes=' ';
}
var html=getNotesHtml(ccode,notes);
var tdId=ccode+'_NotesCell';
var td=dwr.util.byId(tdId);
td.innerHTML=html;
}
});
}
function saveCountryNotes(ccode)
{
var editBox=dwr.util.byId(ccode+'NotesEditBox');
var newNotes=editBox.value;
CountryDB.saveCountryNotes(ccode,newNotes, {
callback:function(newNotes)
{
var ccode=newNotes[0];
var notes=newNotes[1];
var notesHtml=getNotesHtml(ccode,notes);
var td=dwr.util.byId(ccode+&quot;_NotesCell&quot;);
td.innerHTML=notesHtml;
}
});
}
</pre>
<p>There are lots of functions for table samples, and we go through each one of them.
The fi rst is the selectLetter()function. This function gets the selected letter
from the select element and calls the CountryDB.getCountries() remoted Java
method. The callback function is setCountryRows. This function receives the return
value from the Java getCountries() method, that is List<List<String>>, a List
of Lists of Strings.</p>
<p>The second function is addLetters(letters), and it is a callback function for
theAppContent.getLetters() method, which simply returns letters from A to Z.
The addLetters() function uses the DWR utility functions to populate the letter list.
Th en there is a callback function for the CountryDB.getCountries() method. The
parameter for the function is an array of countries that begin with a specifi ed letter.
Each array element has a format: Name, Long name, (country code) Code, Capital,
Notes. The purpose of this function is to populate the table with country data; and
let's see how it is done. The variable, cellFuncs, holds functions for retrieving data
for each cell in a column. The parameter named data is an array of country data that
was returned from the Java class.</p>
<p>The table is populated using the DWR utility function, addRows(). The cellFuncs
variable is used to get the correct data for the table cell. The cellCreator function is
used to create custom HTML for the table cell. Default implementation generates just
a td element, but our custom implementation generates the td-element with the div
placeholder for user notes.</p>
<p>The getNotesHtml() function is used to generate the div element with the event
listener for double-click.</p>
<p>The editCountryNotes() function is called when the table cell is double-clicked.
The function creates input fi elds for editing notes with the Save and Cancel buttons.
The cancelEditNotes() and saveCountryNotes()functions cancel the editing of
new notes, or saves them by calling the CountryDB.saveCountryNotes()
Java method.</p>
<p>The following screenshot shows what the sample looks like with the populated table:</p>
<p><img alt="" src="images/2008/12/15.GIF" /></p>
<p>Now that we have added necessary functions to the web page we can test
the application.</p>
<h2>Testing Tables and Lists</h2>
<p>The application should be ready for testing if we have had the test environment
running during development. Eclipse automatically deploys our new code to the
server whenever something changes. So we can go right away to the test page
http://127.0.0.1:8080/DWREasyAjax. On clicking Tables and lists we can see the
page we have developed. By selecting some letter, for example "I" we get a list of all
the countries that start with letter "I" (as shown in the previous screenshot).</p>
<p>Now we can add notes to countries. We can double-click any table cell under Notes.
For example, if we want to enter notes to Iceland, we double-click the Notes cell
in Iceland's table row, and we get the edit box for the notes as shown in the
following screenshot:</p>
<p><img alt="" src="images/2008/12/16.GIF" /></p>
<p>The edit box is a simple text input fi eld. We didn't use any forms. Saving and
canceling editing is done using JavaScript and DWR. If we press Cancel, we get the
original notes from the CountryDB Java class using DWR and saving also uses DWR
to save data. CountryDB.saveCountryNotes() takes the country code and the notes
that the user entered in the edit box and saves them to the CSV fi le. When notes are
available, the application will show them in the country table together with other
country information as shown in the following screenshot:</p>
<p><img alt="" src="images/2008/12/17.GIF" /></p>
<h2>Afterword</h2>
<p>The sample in this section uses DWR features to get data for the table and list from
the server. We developed the application so that most of the application logic is
written in JavaScript and Java beans that are remoted. In principle, the application
logic can be thought of as being fully browser based, with some extensions in
the server.</p>
<h2>Implementing Field Completion</h2>
<p>Nowadays, fi eld completion is typical of many web pages. A typical use case is
getting a stock quote, and fi eld completion shows matching symbols as users type
letters. Many Internet sites use this feature.</p>
<p>Our sample here is a simple license text fi nder. We enter the license name in the
input text fi eld, and we use DWR to show the license names that start with the typed
text. A list of possible completions is shown below the input fi eld. The following is a
screenshot of the fi eld completion in action:</p>
<p><img alt="" src="images/2008/12/18.GIF" /></p>
<p>Selected license content is shown in an iframe element from</p>
<p>http://www.opensource.org.</p>
<h2>Server Code for Field Completion</h2>
<p>We will re-use some of the classes we developed in the last section. AppContent is
used to load the sample page, and the DBUtils class is used in the LicenseDB class.
The LicenseDB class is shown here:</p>
<pre class="brush: java; title: ; notranslate">
package samples;
import java.util.List;
import java.util.Vector;
public class LicenseDB{
private DBUtils dbUtils=new DBUtils();
public LicenseDB()
{
dbUtils.initFileDB(&quot;licenses.csv&quot;);
}
public List&lt;String&gt; getLicensesStartingWith(String startLetters)
{
List&lt;String&gt; list=new Vector&lt;String&gt;();
List&lt;String&gt; licenses=dbUtils.getCSVStrings(startLetters);
for(String license : licenses)
{
list.add(license.split(&quot;,&quot;)[0]);
}
return list;
}
public String getLicenseContentUrl(String licenseName)
{
List&lt;String&gt; licenses=dbUtils.getCSVStrings(licenseName);
if(licenses.size()&gt;0)
{
return licenses.get(0).split(&quot;,&quot;)[1];
}
return &quot;&quot;;
}
}
</pre>
<p>The getLicenseStartingWith()method goes through the license names and
returns valid license names and their URLs. Similar to the data in the previous
section, license data is in a CSV fi le named licenses.csv in the package directory.
The following is an excerpt of the fi le content:</p>
<pre class="brush: java; title: ; notranslate">
Academic Free License, http://opensource.org/licenses/afl-3.0.php
Adaptive Public License, http://opensource.org/licenses/apl1.0.php
Apache Software License, http://opensource.org/licenses/apachepl-1.1.php
Apache License, http://opensource.org/licenses/apache2.0.php
Apple Public Source License, http://opensource.org/licenses/apsl-2.0.php
Artistic license, http://opensource.org/licenses/artisticlicense-
1.0.php
</pre>
<p>There are quite a few open-source licenses. Some are more popular than others
(like the Apache Software License) and some cannot be re-used (like the IBM
Public License).</p>
<p>We want to remote the LicenseDB class, so we add the following to the dwr.xml file.</p>
<pre class="brush: java; title: ; notranslate">
&lt;create creator=&quot;new&quot; javascript=&quot;LicenseDB&quot;&gt;
&lt;param name=&quot;class&quot; value=&quot;samples.LicenseDB&quot;/&gt;
&lt;include method=&quot;getLicensesStartingWith&quot;/&gt;
&lt;include method=&quot;getLicenseContentUrl&quot;/&gt;
&lt;/create&gt;
</pre>
<h2>Client Code for Field Completion</h2>
<p>The following script element will go in the index.jsp page.</p>
<pre class="brush: java; title: ; notranslate">
&lt;script type='text/javascript' src='/DWREasyAjax/dwr/interface/
LicenseDB.js'&gt;&lt;/script&gt;</pre>
<p>The HTML for the field completion is as follows:</p>
<pre class="brush: java; title: ; notranslate">
&lt;h3&gt;Field completion&lt;/h3&gt;
&lt;p&gt;Enter Open Source license name to see it's contents.
&lt;/p&gt;
&lt;input type=&quot;text&quot; id=&quot;licenseNameEditBox&quot; value=&quot;&quot; onkeyup=&quot;showPopup
Menu()&quot; size=&quot;40&quot;/&gt;
&lt;input type=&quot;button&quot; id=&quot;showLicenseTextButton&quot; value=&quot;Show license
text&quot; onclick=&quot;showLicenseText()&quot;/&gt;
&lt;div id=&quot;completionMenuPopup&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;licenseContent&quot;&gt;&lt;/div&gt;
</pre>
<p>The input element, where we enter the license name, listens to the onkeyup event
which calls the showPopupMenu() JavaScript function. Clicking the Input button calls
the showLicenseText() function (the JavaScript functions are explained shortly).
Finally, the two div elements are place holders for the pop-up menu and the iframe
element that shows license content.</p>
<p>For the pop-up box functionality, we use existing code and modify it for our purpose
(many thanks to http://www.jtricks.com). The following is the popup.js file,
which is located under the WebContent | js directory.</p>
<pre class="brush: java; title: ; notranslate">
jtricks.com/javascript/window/box.html
*
* Modified by Sami Salkosuo.
*/
// Moves the box object to be directly beneath an object.
function move_box(an, box)
{
var cleft = 0;
var ctop = 0;
var obj = an;
while (obj.offsetParent)
{
cleft += obj.offsetLeft;
ctop += obj.offsetTop;
obj = obj.offsetParent;
}
box.style.left = cleft + 'px';
ctop += an.offsetHeight + 8;
// Handle Internet Explorer body margins,
// which affect normal document, but not
// absolute-positioned stuff.
if (document.body.currentStyle &amp;amp;&amp;amp;
document.body.currentStyle['marginTop'])
{
ctop += parseInt(
document.body.currentStyle['marginTop']);
}
box.style.top = ctop + 'px';
}
var popupMenuInitialised=false;
// Shows a box if it wasn't shown yet or is hidden
// or hides it if it is currently shown
function show_box(html, width, height, borderStyle,id)
{
// Create box object through DOM
var boxdiv = document.getElementById(id);
boxdiv.style.display='block';
if(popupMenuInitialised==false)
{
//boxdiv = document.createElement('div');
boxdiv.setAttribute('id', id);
boxdiv.style.display = 'block';
boxdiv.style.position = 'absolute';
boxdiv.style.width = width + 'px';
boxdiv.style.height = height + 'px';
boxdiv.style.border = borderStyle;
boxdiv.style.textAlign = 'right';
boxdiv.style.padding = '4px';
boxdiv.style.background = '#FFFFFF';
boxdiv.style.zIndex='99';
popupMenuInitialised=true;
//document.body.appendChild(boxdiv);
}
var contentId=id+'Content';
var contents = document.getElementById(contentId);
if(contents==null)
{
contents = document.createElement('div');
contents.setAttribute('id', id+'Content');
contents.style.textAlign= 'left';
boxdiv.contents = contents;
boxdiv.appendChild(contents);
}
move_box(html, boxdiv);
contents.innerHTML= html;
return false;
}
function hide_box(id)
{
document.getElementById(id).style.display='none';
var boxdiv = document.getElementById(id+'Content');
if(boxdiv!=null)
{
boxdiv.parentNode.removeChild(boxdiv);
}
return false;
}
//--&gt;&lt;/script&gt;
</pre>
<p>Functions in the popup.js fi le are used as menu options directly below the edit box.</p>
<p>The show_box()function takes the following arguments: HTML code for the
pop-up, position of the pop-up window, and the "parent" element (to which the
pop-up box is related). The function then creates a pop-up window using DOM. The
move_box()function is used to move the pop-up window to its correct place under
the edit box and the hide_box()function hides the pop-up window by removing the
pop-up window from the DOM tree.</p>
<p>In order to use functions in popup.js, we need to add the following script-element
to the index.jsp file:</p>
<pre class="brush: java; title: ; notranslate">
&lt;script type='text/javascript' src='js/popup.js'&gt;&lt;/script&gt;
</pre>
<p>Our own JavaScript code for the fi eld completion is in the index.jsp file. The
following are the JavaScript functions, and an explanation follows the code:</p>
<pre class="brush: java; title: ; notranslate">
function showPopupMenu()
{
var licenseNameEditBox=dwr.util.byId('licenseNameEditBox');
var startLetters=licenseNameEditBox.value;
LicenseDB.getLicensesStartingWith(startLetters, {
callback:function(licenses)
{
var html=&quot;&quot;;
if(licenses.length==0)
{
return;
}
if(licenses.length==1)
{
hidePopupMenu();
licenseNameEditBox.value=licenses[0];
}
else
{
for (index in licenses)
{
var licenseName=licenses[index];//.split(&quot;,&quot;)[0];
licenseName=licenseName.replace(/\&quot;/g,&quot;&quot;&quot;);
html+=&quot;&lt;div style=\&quot;border:1px solid #777777;
margin-bottom:5;\&quot; onclick=
\&quot;completeEditBox('&quot;+licenseName+&quot;');
\&quot;&gt;&quot;+licenseName+&quot;&lt;/div&gt;&quot;;
}
show_box(html, 200, 270, '1px solid','completionMenuPopup');
}
}
});
}
function hidePopupMenu()
{
hide_box('completionMenuPopup');
}
function completeEditBox(licenseName)
{
var licenseNameEditBox=dwr.util.byId('licenseNameEditBox');
licenseNameEditBox.value=licenseName;
hidePopupMenu();
dwr.util.byId('showLicenseTextButton').focus();
}
function showLicenseText()
{
var licenseNameEditBox=dwr.util.byId('licenseNameEditBox');
licenseName=licenseNameEditBox.value;
LicenseDB.getLicenseContentUrl(licenseName,{
callback:function(licenseUrl)
{
var html='&lt;iframe src=&quot;'+licenseUrl+'&quot; width=&quot;100%&quot;
height=&quot;600&quot;&gt;&lt;/iframe&gt;';
var content=dwr.util.byId('licenseContent');
content.style.zIndex=&quot;1&quot;;
content.innerHTML=html;
}
});
}
</pre>
<p>The showPopupMenu() function is called each time a user enters a letter in the
input box. The function gets the value of the input fi eld and calls the LicenseDB.
getLicensesStartingWith() method. The callback function is specifi ed in the
function parameters. The callback function gets all the licenses that match the
parameter, and based on the length of the parameter (which is an array), it either
shows a pop-up box with all the matching license names, or, if the array length is
one, hides the pop-up box and inserts the full license name in the text fi eld. In the
pop up box, the license names are wrapped within the div element that has an
onclick event listener that calls the completeEditBox() function.</p>
<p>The hidePopupMenu()function just closes the pop-up menu and the
competeEditBox() function inserts the clicked license text in the input box
and moves the focus to the button. The showLicenseText() function is called
when we click the Show license text button. The function calls the LicenseDB.
getLicenseContentUrl() method and the callback function creates an iframe
element to show the license content directly from http://www.opensource.org, as
shown in the following screenshot:</p>
<p><img alt="" src="images/2008/12/19.GIF" /></p>
<h2>Afterword</h2>
<p>Field completion improves user experience in web pages and the sample code in this
section showed one way of doing it using DWR.</p>
<p>It should be noted that the sample for fi eld completion presented here is only for
demonstration purposes.</p>
<h2>Summary</h2>
<p>This chapter provided samples for a couple of common tasks that are used in web
development: tables and lists, fi eld completion, and even a generic frame, called a
dynamic user interface, for our sample code. Both the tables and lists sample and the
fi eld completion sample had a very simple CSV-based "database" that holds the data
for our purposes, and both had a remoted method that DWR uses to get the data
from the server and show it in the client.</p>
<p>We also saw some good examples of HTML, CSS, and JavaScript. In fact, without
knowledge of JavaScript it would be diffi cult to write web applications.
Many years ago, as some of you may remember, JavaScript was a dirty word in web
development and no self-respecting developer would touch JavaScript. But change
is a part of life, and in this case, change has been for the better. JavaScript and Java
work very well together with the DWR in between.</p>
<p>The next chapter continues with the user interface part, and shows a couple more
samples, including a map scrolling functionality, similar to what is found in the
popular Google Maps website.
// ]]&gt;</script></em></em></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/12/dwr-java-ajax-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX &#8211; Conversation with an Ajaxian</title>
		<link>http://www.javabeat.net/2008/04/ajax-conversation-with-an-ajaxian/</link>
		<comments>http://www.javabeat.net/2008/04/ajax-conversation-with-an-ajaxian/#comments</comments>
		<pubDate>Thu, 10 Apr 2008 12:18:51 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=174</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>AJAX &#8211; Conversation with an Ajaxain Session 1: What is Ajax? Scene: Friday evening at Malcolms cafe-a pub downtown frequented by Geeks: Me : (jostling my way through the crowd) Where can I find the Ajaxian? Bartender (pointing to a table on the far corner) Last table on the right. Me : (interrupting an animated [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1>AJAX &#8211; Conversation with an Ajaxain</h1>
<h2>Session 1: What is Ajax?</h2>
<h3>Scene: Friday evening at Malcolms cafe-a pub downtown frequented by Geeks:</h3>
<p><strong><em>Me : </em></strong> (jostling my way through the crowd) Where can I find the Ajaxian?</p>
<p>Bartender (pointing to a table on the far corner) Last table on the right.</p>
<p><strong><em>Me : </em></strong> (interrupting an animated conversation on the <strong><em>Me : </em></strong>rits of social networking)<br />
Excuse <strong><em>Me : </em></strong>! I am looking for the Ajaxian.</p>
<p>Geek (pointing to a guy in black T-shirt and jeans) That’s him at the dart<br />
board.<br />
I waited till the ga<strong><em>Me : </em></strong> was over.</p>
<p><strong><em>Me : </em></strong> Hi! You must be the Ajaxian. I am Raj’s friend.</p>
<p>Ajaxian You are ten minutes late. Let’s move over to the reading room where it will be quieter. A reading room in a pub! This must be the first, I thought.</p>
<p><strong><em>Me : </em></strong> Thanks for <strong><em>Me : </em></strong>eting <strong><em>Me : </em></strong>.</p>
<p>Ajaxian No sweat, pal. How much of Ajax do you know?</p>
<p><strong><em>Me : </em></strong> Pretty little except that it is extensively used by the likes of Google.</p>
<p>Ajaxian Why this sudden interest in Ajax?</p>
<p><strong><em>Me : </em></strong> I am developing this highly interactive application that needs to perform a series of server hits at various stages of the user input. Conventional Web applications seem to take painfully long to refresh pages, rendering the application useless.</p>
<p>Ajaxian How many years of programming experience do you have? And what are the types of projects that you have done?<br />
I was being questioned to determine my suitability to satisfy His Holinesss criteria. He was watching <strong><em>Me : </em></strong> keenly. I felt nervous. Even the interview for my first job was easy in comparison to this.</p>
<p><strong><em>Me : </em></strong> For the last five years. I did a Field Force Automation application that ran off the Web used by Reps. Then I have been involved in a couple of intranets used by the staff <strong><em>Me : </em></strong>mbers of a multinational over a secure network. These projects have been developed on Java and Microsoft technologies.</p>
<p>Ajaxian Good. Only a Web developer with a minimum of two years of live applications that cater to a user base of over five hundred users can truly appreciate what we will be discussing. You just about <strong><em>Me : </em></strong>et that criterion. Else, I would have treated you to beer and a ga<strong><em>Me : </em></strong> of darts and wished you good-bye. I passed the test, I guess.</p>
<p>Ajaxian Do you know the history of Ajax?</p>
<p>I shook my head. This was like a classroom. Never had beer in one though. Ajaxian Let <strong><em>Me : </em></strong> quote Mr Jesse Ja<strong><em>Me : </em></strong>s Garnett. In an article, so<strong><em>Me : </em></strong>ti<strong><em>Me : </em></strong> in 2005, he wrote “Web interaction designers can’t help but feel a little envious of our colleagues who create desktop software. Desktop applications have a richness and responsiveness that has<br />
see<strong><em>Me : </em></strong>d out of reach on the Web. The sa<strong><em>Me : </em></strong> simplicity that<br />
enabled the Web’s rapid proliferation also creates a gap between the experiences we can provide and the experiences users can get from a desktop application &#8230;.” The article describes how the early adopters like Google Suggest, Google Maps, Gmail, and Flickr used it to create a whole new user experience to browser applications.</p>
<p><strong><em>Me : </em></strong> But why call it Ajax? It seems that so<strong><em>Me : </em></strong>one struggled to fit an<br />
acronym.</p>
<p>Ajaxian True. Again to quote Garnett &#8220;… I needed so<strong><em>Me : </em></strong>thing shorter than ‘Asynchronous JavaScript+CSS+DOM+XMLHttp Request’ to use when discussing this approach with clients.” The fact is that<br />
the na<strong><em>Me : </em></strong> has co<strong><em>Me : </em></strong> to stay and is accepted in the industry.</p>
<p><strong><em>Me : </em></strong> So Ajax is Asynchronous JavaScript and XML.</p>
<p>Ajaxian Do you know the key difference between a classical Web application and an Ajax-enabled one?</p>
<p><strong><em>Me : </em></strong> (<strong><em>Me : </em></strong>ekly) Is it the high use of JavaScript?</p>
<p>Ajaxian The difference is in the approach. It is a whole new way in which you architect a Web application to make it seem closer to a richclient application. The tools, as a developer, you use are the sa<strong><em>Me : </em></strong>—HTML to display a page, JavaScript to build so<strong><em>Me : </em></strong> intelligence on the browser side, and a server-side scripting using Java, PHP, Visual Basic, etc. for backend processing.</p>
<p><strong><em>Me : </em></strong> I see no difference.</p>
<p>Ajaxian Simply put, a normal Web application refreshes a whole page when any change has to be made on the screen, while in an Ajax-enabled application only that part of the browser screen that needs to be refreshed gets updated.</p>
<p><strong><em>Me : </em></strong> Does this <strong><em>Me : </em></strong>an that clicking on the next-page button of a Webmail application causes the request to be sent to the server and  the response from the server causes the whole page to be &#8220;repainted&#8221; in a typical Web application? While in the Ajaxversion of the sa<strong><em>Me : </em></strong>, the request to the server causes data to be received by the browser which would update the relevant portions of the screen using JavaScript.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Ajaxian Perfect. This can be best understood by a diagram. Let’s move to the white board at that corner.<br />
A café with a white board too! He sketches a diagram. Ajaxian Notice that in a normal Web application, every user interaction, i.e. click of a button, or <strong><em>Me : </em></strong>nu item, or link, or so<strong><em>Me : </em></strong>ti<strong><em>Me : </em></strong>s even shortcut keys, results in an HTTP request sent to the server. The server processes the request and generates a fresh HTML page using server-side scripts. This response stream traverses back to the browser which, then, renders the sa<strong><em>Me : </em></strong> on the screen. During<br />
this ti<strong><em>Me : </em></strong>, the user is dwindling his thumb. </p>
<p><strong><em>Me : </em></strong> That’s when the browser is in a frozen stage, right?</p>
<p>Ajaxian That’s correct. Now, compare this to an Ajax scenario. Here, the user interaction, like before, causes an HTTP request to be sent to the server. The server, like before, processes the request and sends the response in the form of data back to the browser. Now, the browser parses this data and updates the page.</p>
<p><strong><em>Me : </em></strong> Ah! That is the reason why you <strong><em>Me : </em></strong>ntioned that there is no screen refresh.</p>
<p>Ajaxian Yes, however, while the request is being serviced by the server, the user—and the browser—is free to let another interaction happen. Thus, the user can make a second server request, and while that is being serviced, the response from the earlier request could get refreshed on the screen.</p>
<p><strong><em>Me : </em></strong> Interesting. Then, are there any prerequisites for Ajax to work?</p>
<p>Ajaxian Re<strong><em>Me : </em></strong>mber, this is <strong><em>Me : </em></strong>rely a new approach to Web develop<strong><em>Me : </em></strong>nt. Thus, there are no external software components that it requires on the browser side as well as the server side to enable it. However, like any other Web application, it rides over the HTTP layer.</p>
<p><strong><em>Me : </em></strong> Does this <strong><em>Me : </em></strong>an that it will work on all browsers?</p>
<p>Ajaxian The popular ones like Microsoft Internet Explorer 5.5 upwards, Mozilla 1.1 upwards, Safari, and Opera all support Ajax. Basically, it requires a browser to support asynchronous server communication using what is called as &#8220;xml-http-request.&#8221; Support for other technologies like Docu<strong><em>Me : </em></strong>nt Object Model or DOM and<br />
Cascading Style Sheets or CSS are required. JavaScript is the scripting tool that is required to &#8220;package&#8221; all these together.</p>
<p><strong><em>Me : </em></strong> If I disabled JavaScript on my browsers, Ajax applications would<br />
fail, isn’t it?</p>
<p>Ajaxian Mate, if you disabled JavaScript, there is pretty little that will work on the Web today. But, yes, you are right! These applications won’t work.</p>
<p><strong><em>Me : </em></strong> What, then, are the true benefits of Ajax?</p>
<p>Ajaxian (gulping so<strong><em>Me : </em></strong> beer he looked sternly) Why don’t you try answering that based on what you have heard?</p>
<p><strong><em>Me : </em></strong> (so<strong><em>Me : </em></strong>what nervous) Firstly, the user has a much richer experience due to the faster response. This is especially so in input-formsbased screen where the input of one field could instantaneously cause additional inputs in the form…</p>
<p>Ajaxian better context-sensitive form manipulation,</p>
<p><strong><em>Me : </em></strong> … and the user could simultaneously continue working while waiting for a response from an earlier request.</p>
<p>Ajaxian The benefits to an application architect and a developer are enormous. The steps for any given activity can now be broken down into smaller simpler steps. This renders itself to a serviceoriented structure using smaller components of code that are easy to develop and manage. The overall bandwidth required is also much lesser when using Ajax.</p>
<p><strong><em>Me : </em></strong> How is that?</p>
<p>Ajaxian This is so because the response from the server that traverses over the network is only the updated data and not the full Web page. This results in applications appearing more efficient or rendering themselves &#8220;workable&#8221; even in low-bandwidth environ.</p>
<p><strong><em>Me : </em></strong>nts.</p>
<p><strong><em>Me : </em></strong> Yes. I did not think of it in that fashion. Now I get an idea as to<br />
why the industry is going all agog with Ajax.</p>
<p>Ajaxian Would you like a print of this diagram? He pressed a key and a print out appeared on a printer attached alongside. Wow!</p>
<p>KEY POINTS</p>
<ul>
<li>1. Ajax is a whole new approach to Web develop<strong><em>Me : </em></strong>nt.</li>
<li>2. Ajax stands for Asynchronous Java and XML.</li>
<li>3. Mr. Jesse Ja<strong><em>Me : </em></strong>s Garnett originally coined this acronym.</li>
<li>4. Ajax code is written in JavaScript and uses Docu<strong><em>Me : </em></strong>nt Object Model (DOM)<br />
objects and Cascading Style Sheets (CSS) concepts.</li>
<li>5. Ajax causes a browser to get updated without a full screen refresh.</li>
<li>6. Simply put, an Ajax call causes a request to be submitted to the concerned</li>
<li>Web server and waits for the results from that server. Then, it extracts the<br />
information received and updates the screen.</li>
<li>7. While an Ajax operation is “on,” the user can interact with the browser to<br />
perform other “clicks.”</li>
<li>8. Popular sites that use Ajax include Google Mail, Google Maps, and Flickr.</li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/04/ajax-conversation-with-an-ajaxian/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX Support in Struts 2.0</title>
		<link>http://www.javabeat.net/2007/06/ajax-support-in-struts-2-0/</link>
		<comments>http://www.javabeat.net/2007/06/ajax-support-in-struts-2-0/#comments</comments>
		<pubDate>Sat, 09 Jun 2007 01:44:38 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Struts 2.0]]></category>
		<category><![CDATA[Web Frameworks]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=54</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Ajax or Asynchronous JavaScript and XML was introduced by Jesse James Garrett in 2005. He is called the “Father of Ajax” .Ajax is a collection of concepts and technologies that allows richer and more interactive user interaction with the web applications. The Ajax engine allows the user’s interaction with the application to happen asynchronously — [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><span style="font-size: 13px;">Ajax or Asynchronous JavaScript and XML was introduced by Jesse James Garrett in 2005. He is called the “Father of Ajax” .Ajax is a collection of concepts and technologies that allows richer and more interactive user interaction with the web applications. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.</span></p>
<h2>Who is using AJAX</h2>
<p>The most popular and the biggest user of AJAX is Google. Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps — are Ajax applications Google mail, Google calendar and Google home page are some examples. In your Google mailbox the “loading” that is displayed in the top right corner is using these Ajax technologies. The new Yahoo homepage too uses some of these technologies. Another cool Ajax implemented website would be <a href="http://www.pageflakes.com">www.pageflakes.com</a> Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar techniques.</p>
<h2>The BackScreen of Ajax</h2>
<p>In traditional webpages, the pages will be reloaded for each and every request. But in most of the cases only a part of the page will be processed. Hence such a page reload is unnecessary. <strong>Thus the usage of ajax plays a efficient role. In the webpages, that are using ajax, only the part of the page that has to be processed will be transferred to the web server and the processed data will be loaded in the page without a page reload.</strong></p>
<h2>AJAX internals</h2>
<p>AJAX is not a single technology as mentioned earlier. It is important to remember that AJAX is not Java or .NET dependent.</p>
<p>Whatever be your back end code, you can use AJAX to communicate with it. People prefer AJAX for the high speed with which it works. It does it with three basic ways</p>
<ul style="list-style-type: decimal;">
<li>Better utilization of browser cache</li>
<li>Batching up of network requests in a single packet to reduce network latency issues</li>
<li>Decreasing the workload on the server by not requiring it to process the entire page</li>
</ul>
<h2>Where can we use AJAX</h2>
<dl>
<dt>Forms:</dt>
<dd>Web based forms are slow. AJAX can definitely improve the performance of web-based formsUser Communication:</dd>
<dd>User communications like chat pages, voting’s and ratings can be done efficiently using AJAX</dd>
<dt>News:</dt>
<dd>RSS feed is another popular concept where AJAX can be used</dd>
<dt>Data Manipulation:</dt>
<dd>This includes some sort of filtering data, selecting names from one combo box to another, sorting data, invoking the suggest criteria or a hint</dd>
</dl>
<h2>Defining Ajax</h2>
<p>As we have seen an introduction to AJAX, let us try to define it. Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:</p>
<ul style="list-style-type: circle;">
<li>Standards-based presentation using XHTML and CSS;</li>
<li>Dynamic display and interaction using the Document Object Model;</li>
<li>Data interchange and manipulation using XML and XSLT;</li>
<li>Asynchronous data retrieval using XMLHttpRequest;</li>
</ul>
<p>And JavaScript binding everything together.<br />
So, how does AJAX does this sending request and getting response from the backend server??</p>
<p>Using the XML Http Request object.</p>
<h2>XML Http Request object</h2>
<p>The XML HttpRequest was introduced by Microsoft in Internet Explorer 5.0. Recently , Mozilla and apple have included support for this in their web browsers(Firefox and Safari).This object is the fundamental basis for Ajax. Microsoft implementation is different from that of other web browsers, so when you create this object in your code, you need to do a typical browser check.</p>
<p>For Internet Explorer, we can create this object using,</p>
<p><strong>Var req = new ActiveXObject(“Microsoft.XMLHTTP”);</strong></p>
<p>For firefox and safari,</p>
<p><strong>Var req = new XMLHttpRequest();</strong></p>
<h2>Struts and Ajax in Action</h2>
<p>As we have seen enough of the theory behind the working of Ajax in struts let us see an example. Simple example is loading a drop down depending on the selected item in another drop down. We need to populate the characters in a “showcharacters” dropdown when a particular TV Show is selected in the “showTVShow” drop down using AJAX. Let us see the Ajax request response cycle for this scenario.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2007/06/1.bmp"><img class="aligncenter  wp-image-2288" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2007/06/1.bmp" width="352" height="351" /></a></p>
<p><center>Fig 1.1 Ajax Request Response Cycle</center></p>
<h3>Step 1: Create a jsp page (“tvshow.jsp”)</h3>
<p>Let us take three TV shows which I like.”Lisse Maguire”,” That’s so Raven” and “Dhoom Machallo Dhoom”. We need to populate the characters dropdown as and when the TV Show dropdown value changes , so we decide to call the javascript in the “onchange()” of the select box.</p>
<pre class="brush: java; title: ; notranslate">&lt;html:form action=&quot;showCharacters.do&quot;&gt;
		TV Show:
		&lt;html:select property=&quot;TVShowSelect&quot;
						onchange=&quot;retrieveURL(' showCharacters.do?tvShow=' + this.value);&quot;&gt;
			&lt;html:option value=&quot;Lissie Maguire&quot;&gt; Lissie Maguire &lt;/html:option&gt;
			&lt;html:option value=&quot;That’s so Raven&quot;&gt; That’s so Raven &lt;/html:option&gt;
			&lt;html:option value=&quot;Dhoom machale&quot;&gt; Dhoom machale &lt;/html:option&gt;
		&lt;/html:select&gt;
		&lt;br&gt;
		Characters: &lt;span id=&quot;characters&quot;&gt;&lt;/span&gt;
	&lt;/html:form&gt;	</pre>
<p>Here we are sending a URL to the Java script function.</p>
<pre class="brush: java; title: ; notranslate">“’ showCharacters.do?tvShow=' + this.value”</pre>
<p>We are appending the selected item with the URL as a query string. We can also just send the Url and append the form contents in the java script.</p>
<h3>Step:2 Making the AJAX Call to the Server</h3>
<p>In the java script we need to create a XML HttpRequest object</p>
<pre class="brush: java; title: ; notranslate">	function retrieveURL(url)
	{
	if (window.XMLHttpRequest)
	{
	// Non-IE browsers
				req = new XMLHttpRequest();
				req.onreadystatechange = processStateChange;
				try {
					 req.open(&quot;GET&quot;, url, true);
				} catch (e) {
					 alert(e);
				}
				req.send(null);
			} else if (window.ActiveXObject) { // IE

				 req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
				if (req) {
					 req.onreadystatechange = processStateChange;
					 req.open(&quot;GET&quot;, url, true);
					 req.send();
				 }
			}
	  }</pre>
<p>Within the retrieveURL() method, the line req.onreadystatechange = processStateChange (note: no brackets) tells the browser to call the processStateChange() method once the server sends back its response. This method (now standard in AJAX) also determines whether it should use the Internet Explorer (ActiveX) or Netscape/Mozilla (XmlHttpRequest) object to ensure cross-browser compatibility.</p>
<p>Now when the XMLHttpRequest object is created , we ask the browser to call the processstatechange method when we get the response from the server.</p>
<h3>Step 3: Configure action path in struts-config</h3>
<p>This is the same old struts functioning.</p>
<p>“’showCharacters.do” is configured in the struts-config.xml</p>
<p><strong>struts-config.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;action path=&quot;/showCharacters &quot; type=&quot;ShowTVAction&quot; validate=&quot;false&quot; &gt;
			&lt;forward name=&quot;success&quot; path=&quot;/pages/showCharacters.jsp&quot; /&gt;
	&lt;/action&gt;</pre>
<h3>Step 4: Write the action class</h3>
<p>The action class has to get the value selected in the TVShow dropdown and Get the appropriate list of characters using the function getCharacters(String tvShow) .</p>
<pre class="brush: java; title: ; notranslate">public class ShowTVAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm inForm, HttpServletRequest request, HttpServletResponse response) throws Exception {

		 // Get a list of characters associated with the select TV show
		 String tvShow = (String)request.getParameter(&quot;tvShow&quot;);
			if (tvShow == null) {
				 tvShow = &quot;&quot;;
			}
			ArrayList characters = getCharacters(tvShow);
			request.getSession().setAttribute(&quot;characters&quot;, characters);
		 response.setContentType(&quot;text/html&quot;);
		 return mapping.findForward(&quot;success&quot;);
	  } // End execute()

	  // This method returns a list of characters for a given TV show.  If no TV
	  // show is selected, i.e., initial page view, am empty ArrayList is returned.

	  private ArrayList getCharacters (String tvShow) {

		 ArrayList al = new ArrayList();

			if (tvShow.equalsIgnoreCase(&quot;Lissie Mcguire&quot;)) {
				 al.add(&quot;Lizzie Mcguire&quot;);
				 al.add(&quot;Mathew Mcguire&quot;);
				 al.add(&quot;Miranda&quot;);
				 al.add(&quot;Gordon&quot;);
		 }

		 if (tvShow.equalsIgnoreCase(&quot;That’s so Raven &quot;)) {
				al.add(&quot;Raven&quot;);
				al.add(&quot;Chelse”);
				al.add(&quot;Orlanda&quot;);
				al.add(&quot;Victor Backstor&quot;);
				al.add(&quot;Cory Backstor&quot;);
			}

		if (tvShow.equalsIgnoreCase(&quot;Dhoom machale &quot;)) {
				al.add(&quot;Priyanka&quot;);
				al.add(&quot;Koyel&quot;);
				al.add(&quot;Nehal&quot;);
				al.add(&quot;Aadhiraj&quot;);
				al.add(&quot;Maleni&quot;);
			}

			return al;

	  } // End getCharacters()

	} // End class</pre>
<p>Then it sets the Appropriate characters in the session and returns the keyword “success” Thus the control passes to showCharacters.jsp</p>
<h3>Step 5: Write the contents you need to reload in the characters drop down (“ShowCharacters.jsp”)</h3>
<p>In the showCharacters.jsp we load the contents of the characters drop down by taking their values from the session. Remember to add the tag libraries and surround the code with a form tag.</p>
<p><strong>ShowCharacters.jsp</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;html:select property=&quot;TVShowSelect&quot;&gt;
		  &lt;logic:present name=&quot;characters&quot;&gt;
				&lt;%ArrayList ch = (ArrayList)  request.getSession().getAttribute(&quot;characters&quot;);
				String[] s = new String[ch.size()];
				ch.toArray(s);
				for(int i=0;i&lt;s.length;i++)
				{%&gt;
					 &lt;html:option value =&quot;&lt;%=s[i] %&gt;&quot; &gt;&lt;/html:option&gt;
				&lt;%} %&gt;
		  &lt;/logic:present&gt;
	&lt;/html:select&gt;</pre>
<p>Thus the showCharacters.jsp is the response from the Back end server. Once the response form the server is got by the browser. It calls the processStateChange() method</p>
<h3>Step 6: Updating the Web Page with the AJAX Response</h3>
<p>So far, we have looked at the JavaScript to do the AJAX call (listed above) and the Struts Action, ActionForm, and JSP (mostly the same, with the addition of tags). To complete our understanding of the Struts-AJAX project, we need to look at the following JavaScript function that is responsible for updating the current web page when the results from the server are received.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>processStateChange(): The method name that we set before making the AJAX call. The XMLHttpRequest/Microsoft.XMLHTTP object calls this method once the server has completed sending back its response.</p>
<pre class="brush: java; title: ; notranslate">function processStateChange() {
			if (req.readyState == 4) { // Complete
			if (req.status == 200) { // OK response
					document.getElementById(&quot;characters&quot;).innerHTML = req.responseText;
			} else {
				 alert(&quot;Problem: &quot; + req.statusText);
			 }
		 }
	  }</pre>
<p>Here readystate is checked .If it is equal to 4 , it means the response is completely received and the status of the response is checked to 200.</p>
<p>If everything fit in, the response is set as the innerHTML of the span “characters”. We can also give the response to a div.</p>
<p>Thus we have done a asynchronous call to the back end and got the response and set it to a span element. Only the contents of the span have been reloaded while the rest of the page remained there.</p>
<h2>Flow of Control</h2>
<p>By adding the above JavaScript code to our application, the following steps now happen on the server and on the browser.</p>
<ul style="list-style-type: decimal;">
<li>The page loads as per a normal Struts application.</li>
<li>The user changes a dropdown value, triggering an onChange() event, which calls the retrieveURL() JavaScript function</li>
<li>This JavaScript function makes a (background) call to the Struts Action on the server</li>
<li>This JavaScript function also sets the name of a second JavaScript function, which will be called when the server response is finished. In this case, it is set to the processStateChange() method.</li>
<li>As expected, when the server response is finished, the processStateChange() method is called.</li>
<li>The JavaScript sets the response to a span in the page</li>
</ul>
<h2>New Features in Struts 2.0 for AJAX</h2>
<p>One of the useful enhancements in Struts 2.0 is the introduction of AJAX Theme</p>
<p>The Ajax theme extends the xhtml theme with AJAX features. The theme uses the popular DOJO AJAX/JavaScript toolkit. The new AJAX features include:</p>
<ul style="list-style-type: disc;">
<li>AJAX Client Side Validation</li>
<li>Remote form submission support (works with the submit tag as well)</li>
<li>An advanced div template that provides dynamic reloading of partial HTML</li>
<li>An advanced a template that provides the ability to load and evaluate JavaScript remotely</li>
<li>An AJAX-only tabbed Panel implementation</li>
<li>A rich pub-sub event model</li>
<li>Interactive auto complete tag</li>
</ul>
<p>The framework provides a set of tags to help you ajaxify your applications, on Dojo.</p>
<p>To use the Ajax tags you need to set the &#8220;theme&#8221; attribute to &#8220;Ajax&#8221;.<strong>Use the head tag to configure the page for the Ajax theme.</strong></p>
<h3>URL</h3>
<p>The &#8220;href&#8221; attribute must contain a url built with the URL tag<br />
Example:</p>
<pre class="brush: java; title: ; notranslate"> Initial Content</pre>
<p>Set the &#8220;debug&#8221; attribute of the head tag to &#8220;true&#8221; to display debug information on the bottom of the page</p>
<h3>Indicators</h3>
<p>Use indicators to notify the user that a request is in progress. The indicator should be hidden when the page is loaded.</p>
<h3>Dynamic Div</h3>
<p>The div tag is a content area that can load its content asynchronously. The div tag can be forced to reload its content using topics. To define the topics that will trigger the refresh of the panel, use the &#8220;listenTopics&#8221; attribute. This tag will load its content when the page is loaded, unless &#8220;autoStart&#8221; is set to &#8220;false&#8221;.<br />
While Dojo supports crossdomain XHR using IFrames, the S2 Ajax tags do not (yet)</p>
<p>This div will refresh every time the topics &#8220;/refresh0&#8243; or &#8220;/refresh1&#8243; are published:</p>
<p>to publish a topic use.</p>
<pre class="brush: java; title: ; notranslate">dojo.event.topic.publish(&quot;/refresh”);</pre>
<h3>Retrieve Remote Data</h3>
<p>The simplest way to use the div tag is to provide an href attribute. For example</p>
<p>What this does after the HTML page is completely loaded; the specified URL will be retrieved asynchronously in the browser. The entire contents returned by that URL will be injected in to the div and will update every minute after a two second delay: Include the attribute errorText in case the URL is not loaded</p>
<pre class="brush: java; title: ; notranslate">errorText=&quot;Unable to contact weather server&quot;</pre>
<h3>Submit</h3>
<p>The submit tag can be used to update the content of its &#8220;targets&#8221; attribute with text returned from the asynchronous request. &#8220;targets&#8221; is a comma-delimited list of element ids. The &#8220;targets&#8221; attribute is optional.</p>
<p>Regular submit button that will update the content of div1:</p>
<div id="div1">Div 1</div>
<p>For using Submit button using an image add the attribute src</p>
<pre class="brush: java; title: ; notranslate">src=&quot;${pageContext.request.contextPath}/images/struts-rocks.gif&quot;</pre>
<p>If the submit button is used inside a form (href is not required on this case), the form will be submitted asynchronously using<br />
A submit button can be used to submit a form, even if it is outside the form, using &#8220;formId&#8221;, &#8220;formFilter&#8221; and &#8220;href&#8221;. Note that in this case &#8220;href&#8221; is required.</p>
<pre class="brush: java; title: ; notranslate"> &lt;input type=&quot;textbox&quot; name=&quot;data&quot; /&gt;</pre>
<h3>Anchor</h3>
<p>The anchor tag, like the submit tag; can be used to update the content of its &#8220;targets&#8221; attribute with text returned from the asynchronous request. &#8220;Targets&#8221; is a comma-delimited list of element ids. The &#8220;targets&#8221; attribute is optional.</p>
<p>This anchor will update the content of div1 and div2 with text returned form &#8220;/AjaxTest.action&#8221;</p>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<p>Update divs If the anchor tag is used inside a form (href is not required on this case), the form will be submitted asynchronously:</p>
<pre class="brush: java; title: ; notranslate">
	  &lt;input type=&quot;textbox&quot; name=&quot;data&quot; /&gt;
	  Submit form</pre>
<p>Using the anchor tag to submit a form:</p>
<pre class="brush: java; title: ; notranslate">
	  &lt;input type=&quot;textbox&quot; name=&quot;data&quot; /&gt;

	Submit form</pre>
<h3>AJAX Client Side Validation</h3>
<ul style="list-style-type: disc;">
<li>Ajax Validation requires DWR servlet being setup, Dojo and the Ajax theme being used.</li>
<li>In the Ajax theme, DWR is used for normal validation while Dojo handles everything else (widgets, XHR, browser JS events etc.)</li>
<li>In order for validation to function properly it is advised to use standard Struts Tags</li>
</ul>
<h3>Setup DWR</h3>
<p>DWR could be setup by having the following dwr configuration (dwr.xml) at /WEB-INF/ directory. If it needs to be in other places.</p>
<p>A DWRServlet need to be registered with the web application as well. The following shows a typical web.xml with DWRSerlvet.</p>
<pre class="brush: java; title: ; notranslate">
		   dwr
		   uk.ltd.getahead.dwr.DWRServlet

			   debug
			   true

	&lt;!-- JavaServer Faces Servlet Configuration, not used directly --&gt;

		faces
		javax.faces.webapp.FacesServlet
		1

		&lt;!-- JavaServer Faces Servlet Mapping, not called directly --&gt;

		   faces
		   *.action

		   dwr
		   /dwr/*</pre>
<h3>Add a form attribute</h3>
<p>Add the attribute validate to the. The validate=&#8221;true&#8221; option is set for thetag to enable onblur-triggered validation</p>
<pre class="brush: java; title: ; notranslate">Validation - Basic</pre>
<p>Now as usual have a form bean for this form with getters and setters and constructors, and configure the validation.xml for required fields</p>
<pre class="brush: java; title: ; notranslate">You must enter a name1319
				Only people ages 13 to 19 may take this quiz</pre>
<h2>Summary</h2>
<p>This is a simple introduction to Ajax.Start implementing it and you will find it simple, easy and attractive. One can use it to do many different things. It all accounts your creativity. It is a good approach in many cases, but will not be appropriate in others. If reaching the maximum possible audience is your goal, you would want to stay away from this. If a user disabling scripting in their browser might be a concern (and your site wouldn’t be any good without it), this probably isn’t a good answer either. There are other reasons to stay away from it in some situations, but the bottom line is treat it like any other tool in your toolbox: it will be right for some jobs, maybe &#8220;not so&#8221; for others.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/06/ajax-support-in-struts-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
