<?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>ViralPatel.net &#187; AJAX</title> <atom:link href="http://viralpatel.net/blogs/category/ajax/feed" rel="self" type="application/rss+xml" /><link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</title><link>http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html</link> <comments>http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html#comments</comments> <pubDate>Fri, 24 Dec 2010 10:12:54 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JQuery]]></category> <category><![CDATA[authentication]]></category> <category><![CDATA[http error]]></category> <category><![CDATA[jquery ajax tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2118</guid> <description><![CDATA[Since few days I am working on a small project where I have to deal with lot of Ajax requests. The whole UI is designed such that only appropriate parts are refreshed with required information through Ajax. The application needs user authentication before accessing any part of it. Although this is easy to achieve in [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2010/12/security_lock.png" alt="" title="security_lock" width="208" height="153" class="alignright size-full wp-image-2119" />Since few days I am working on a small project where I have to deal with lot of Ajax requests. The whole UI is designed such that only appropriate parts are refreshed with required information through Ajax.</p><p>The application needs user authentication before accessing any part of it. Although this is easy to achieve in any MVC based framework, its a whole new thing when dealing with Ajax requests.</p><p>In a normal request/response based MVC application, if a user is not authenticated and tries to view a webpage, the request is redirected to the Login page. Almost all MVC framework comes with this functionality. When the request gets redirected to Login page, the Status Code 403 (Forbidden) is set in HTTP header. 403 Forbidden is a HTTP status code returned by a web server when a user agent requests a resource that the server does not allow them to.</p><p>But when using Ajax for getting the content, if the request is redirected to Login page, it is difficult to handle this scenario.</p><p>Here is a simplest solution that can be implemented in your Ajax based application. Just add this code in your Javascript file.</p><pre class="brush: jscript; title: ; notranslate">
    $(document).ready(
        function() {
            $(&quot;body&quot;).ajaxError(
                function(e,request) {
                    if (request.status == 403) {
                        window.location.reload();
                        //window.location.href = &quot;/myapp/login&quot;;
                    }
                }
            );
        }
    );
</pre><p>In above code, we have added a handler function to ajaxError which gets called by jQuery whenever there is an error in the HTTP Response. The function checks if the status code is 403, if it is then it simply tries to reload the URL. This generate a new request to the server which automatically gets redirected to the login page. The only disadvantage of reloading the page is that you generate a new HTTP request which server has to handle and redirect to Login page.</p><p>You may wish to directly redirect user to login page from client code itself. Check the Line XX where we are changing the windows location and redirecting user. I personally dont like this method as you have to hard code the path for login page in javascript. I prefer using the previous solution to reload the page.</p><p>I am sure there must be several way of implementing this in Javascript. Share yours if you think you have a better one <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html" title="jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery">jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2009/02/handling-session-timeout-server-errors-http-ajax-session-ajax-session-timeout-problem.html" title="Handling Session timeout &#038; other server http errors in AJAX">Handling Session timeout &#038; other server http errors in AJAX</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html" title="AJAX Post Method example using Javascript &#038; jQuery">AJAX Post Method example using Javascript &#038; jQuery</a></li><li><a href="http://viralpatel.net/blogs/2012/01/scroll-fix-header-jquery-facebook.html" title="Facebook Style Scroll Fixed Header in JQuery">Facebook Style Scroll Fixed Header in JQuery</a></li><li><a href="http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html" title="Create a Clearable TextBox with jQuery">Create a Clearable TextBox with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html" title="jQuery: Get the Text of Element without Child Element">jQuery: Get the Text of Element without Child Element</a></li><li><a href="http://viralpatel.net/blogs/2011/01/first-play-framework-gae-siena-application-tutorial-example.html" title="Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example">Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</title><link>http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html</link> <comments>http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html#comments</comments> <pubDate>Sun, 12 Apr 2009 02:11:16 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JQuery]]></category> <category><![CDATA[javascript framework]]></category> <category><![CDATA[jquery ajax tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1111</guid> <description><![CDATA[jQuery, the JavaScript library provides some powerful set of jQuery AJAX API&#8217;s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an XMLHttpRequest object that depends on the browser and then make an AJAX call. Also sending a form data using [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/jquery-logo.png" alt="jquery-logo" title="jquery-logo" width="236" height="85" class="alignleft size-full wp-image-1108" />jQuery, the JavaScript library provides some powerful set of <strong>jQuery AJAX</strong> API&#8217;s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an <strong>XMLHttpRequest object</strong> that depends on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX.</p><p>jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see different ways of doing AJAX things in jQuery.</p><h2>GET Request method using jQuery</h2><p>Load a remote page using HTTP <strong>GET request</strong> method. This is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code).</p><h3>jQuery.get( url, [data], [callback], [type] )</h3><p><strong>url</strong>: (String) The URL of the page to load.<br /> <strong>data</strong> (Optional): (Map) Key/value pairs that will be sent to the server.<br /> <strong>callback</strong> (Optional): (Function) A function to be executed whenever the data is loaded successfully.<br /> <strong>type</strong> (Optional): (String) Type of data to be returned to callback function: &#8220;xml&#8221;, &#8220;html&#8221;, &#8220;script&#8221;, &#8220;json&#8221;, &#8220;jsonp&#8221;, or &#8220;text&#8221;.<br /> e.g.</p><pre class="brush: jscript; title: ; notranslate">
$.get(
	&quot;http://some-remote-site&quot;,
	&quot;{key:value}&quot;,
	function(data) { alert(data); },
	&quot;html&quot;
);

$.get(
	&quot;http://some-remote-site&quot;,
	function(data) { alert(data); },
);
</pre><h2>POST Request method using jQuery</h2><p>Sending post method is also very easy with jQuery. All you have to do is just to call jQuery.post () method instead of jQuery.get (). Following is the syntax of post method.</p><h3>jQuery.post( url, [data], [callback], [type] )</h3><p><strong>url</strong>: (String) The URL of the page to load.<br /> <strong>data</strong> (Optional): (Map) Key/value pairs that will be sent to the server.<br /> <strong>callback</strong> (Optional): (Function) A function to be executed whenever the data is loaded successfully.<br /> <strong>type</strong> (Optional): (String) Type of data to be returned to callback function: &#8220;xml&#8221;, &#8220;html&#8221;, &#8220;script&#8221;, &#8220;json&#8221;, &#8220;jsonp&#8221;, or &#8220;text&#8221;.</p><pre class="brush: jscript; title: ; notranslate">
$.post(&quot;test.php&quot;, { func: &quot;getNameAndTime&quot; },
  function(data){
    alert(&quot;Hello&quot;);
  }, &quot;json&quot;);
</pre><h2>Get JSON using jQuery</h2><p>JavaScript Object Notation (JSON) is a popular light weight format that can be used to get data from server. JSON has became very popular since that web pages have became interactive using AJAX. JSON format is easy to create from the server and easy to parse at client as it is the basic object representation in JavaScript.</p><p>JQuery provides a function that can be used to make an AJAX call and get the data in JSON format. Normally the data that we get from AJAX is converted in JSON by calling eval () method of JavaScript. But the function provided by JQuery handles this internally and provides direct JSON object as output.</p><h3>jQuery.getJSON( url, [data], [callback] )</h3><pre class="brush: jscript; title: ; notranslate">
$.getJSON(&quot;http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?&quot;,
        function(data){
          $.each(data.items, function(i,item){
            $(&quot;&lt;img/&gt;&quot;).attr(&quot;src&quot;, item.media.m).appendTo(&quot;#images&quot;);
            if ( i == 3 ) return false;
          });
        });
</pre><h2>AJAX Start/End using jQuery</h2><p>While you make an AJAX call and get some data from server, it is good to show a progress bar or image to user so that (s)he knows that something is going on. Hence Loading&#8230; text is common in AJAX enabled application.</p><p>What if you web application is making many AJAX calls like gmail. You may want to display a Loading&#8230; text while any of AJAX call is proceeding. To achieve this <strong>ajaxStart()</strong> and <strong>ajaxComplete()</strong> methods of jQuery can be used.</p><p>ajaxStart() method registers a function handler that will be called by jQuery internally whenever an AJAX call is made. If already a request is active than the handler is not called. We can use this method to register a handler function that will display our progress bar.</p><pre class="brush: jscript; title: ; notranslate">
$.ajaxStart(function() {
	$(&quot;div#loading&quot;).text(&quot;Loading...&quot;);
});
</pre><p>In above code snippet, we used ajaxStart() method to register a function that set the innerHTML of div to Loading&#8230;</p><p>Similarly ajaxComplete() method can be used to register a handler function which gets called by jQuery when an AJAX request get completed and any other active request are not in progress.</p><pre class="brush: jscript; title: ; notranslate">
$.ajaxComplete(function() {
	$(&quot;div#loading&quot;).text(&quot;&quot;);
});
</pre><h2>Serialize html form using jQuery</h2><p>While submitting a form using AJAX, one has to create a input string that contains the value of all the input elements on the screen. It is very difficult to create this string if your form is very big. Hence we can use jQuery&#8217;s <strong>serialize()</strong> and <strong>serializeArray()</strong> method to do so.</p><h3>serialize()</h3><p>Serializes a set of input elements into a string of data. Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks. In order to work properly serialize requires that form fields have a <strong>name attribute</strong>. Having only an id will not work.</p><pre class="brush: jscript; title: ; notranslate">
var str = $(&quot;form&quot;).serialize();
$(&quot;#results&quot;).text(str);
</pre><p>In above code snippet, we created a serialize output of the form. This value can be sent to server by an AJAX call.</p><h3>serializeArray()</h3><p>serializeArray() does the similar job. Except it creates JSON output.</p><pre class="brush: jscript; title: ; notranslate">
[
     {name: 'firstname', value: 'Hello'},
     {name: 'lastname', value: 'World'},
     {name: 'alias'}, // this one was empty
]
</pre><p>If you read this far, you should <a rel="nofollow" href="http://twitter.com/viralpatelnet">follow me on twitter here.</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html" title="jQuery Ajax &#8211; Handling unauthenticated requests via Ajax">jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</a></li><li><a href="http://viralpatel.net/blogs/2009/04/jquery-tabs-create-html-tabs-using-jquery-ui.html" title="jQuery tabs: Create HTML tabs using jQuery UI">jQuery tabs: Create HTML tabs using jQuery UI</a></li><li><a href="http://viralpatel.net/blogs/2009/04/tutorial-handle-browser-events-using-jquery-javascript-framework.html" title="Tutorial: Handle browser events using jQuery JavaScript framework">Tutorial: Handle browser events using jQuery JavaScript framework</a></li><li><a href="http://viralpatel.net/blogs/2009/03/how-to-apply-html-user-interface-effects-using-jquery.html" title="How to apply HTML User Interface Effects using jQuery.">How to apply HTML User Interface Effects using jQuery.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html" title="AJAX Post Method example using Javascript &#038; jQuery">AJAX Post Method example using Javascript &#038; jQuery</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html" title="Sum HTML Textbox Values using jQuery / JavaScript">Sum HTML Textbox Values using jQuery / JavaScript</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html/feed</wfw:commentRss> <slash:comments>45</slash:comments> </item> <item><title>Creating &amp; Parsing JSON data with Java Servlet/Struts/JSP</title><link>http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html</link> <comments>http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html#comments</comments> <pubDate>Thu, 19 Feb 2009 10:34:07 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[json]]></category> <category><![CDATA[JSONObject]]></category> <category><![CDATA[servlet]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=836</guid> <description><![CDATA[JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). The JSON format is specified in RFC 4627 by Douglas Crockford. The official Internet media type for JSON is application/json. The JSON format is often used for transmitting [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/java-logo2-150x150.gif" alt="java logo" title="java-logo2" width="150" height="150" class="alignleft size-thumbnail wp-image-840" /><br /> JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). The JSON format is specified in <a rel="nofollow" target="_new" href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a> by Douglas Crockford. The official Internet media type for JSON is <strong>application/json</strong>.</p><p>The JSON format is often used for transmitting structured data over a network connection in a process called serialization. Its main application is in AJAX web application programming, where it serves as an alternative to the traditional use of the XML format.</p><h2>Supported data types</h2><ol><li>Number (integer, real, or floating point)</li><li>String (double-quoted Unicode with backslash escapement)</li><li>Boolean (true and false)</li><li>Array (an ordered sequence of values, comma-separated and enclosed in square brackets)</li><li>Object (collection of key/value pairs, comma-separated and enclosed in curly brackets)</li><li>null</li></ol><h2>Syntax</h2><p>The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person&#8217;s address, and contains a list of phone numbers (an array).</p><pre class="brush: jscript; title: ; notranslate">
{
    &quot;firstName&quot;: &quot;John&quot;,
    &quot;lastName&quot;: &quot;Smith&quot;,
    &quot;address&quot;: {
        &quot;streetAddress&quot;: &quot;21 2nd Street&quot;,
        &quot;city&quot;: &quot;New York&quot;,
        &quot;state&quot;: &quot;NY&quot;,
        &quot;postalCode&quot;: 10021
    },
    &quot;phoneNumbers&quot;: [
        &quot;212 732-1234&quot;,
        &quot;646 123-4567&quot;
    ]
}
</pre><h2>Creating JSON data in Java</h2><p><a href="http://json.org/java/" rel="nofollow" target="_new">JSON.org</a> has provided libraries to create/parse JSON data through Java code. These libraries can be used in any Java/J2EE project including Servlet, Struts, JSF, JSP etc and JSON data can be created.</p><p>Download JAR file <a href="http://viralpatel.net/blogs/download/json/json-rpc-1.0.jar">json-rpc-1.0.jar (75 kb)</a></p><p>Use JSONObject class to create JSON data in Java. A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get()  and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.</p><pre class="brush: java; title: ; notranslate">
import org.json.JSONObject;

...
...

JSONObject json = new JSONObject();
json.put(&quot;city&quot;, &quot;Mumbai&quot;);
json.put(&quot;country&quot;, &quot;India&quot;);

...

String output = json.toString();

...
</pre><p>Thus by using toString() method you can get the output in JSON format.</p><h2>JSON Array in Java</h2><p>A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt  methods for accessing the values by index, and put methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.</p><p>The constructor can convert a JSON text into a Java object. The toString method converts to JSON text.</p><p>JSONArray class can also be used to convert a collection of Java beans into JSON data. Similar to JSONObject, JSONArray has a put() method that can be used to put a collection into JSON object.</p><p>Thus by using JSONArray you can handle any type of data and convert corresponding JSON output.</p><h2>Using json-lib library</h2><p>JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.</p><p>Json-lib comes in two flavors, depending on the jdk compatibility. json-lib-x.x-jdk13 is compatible with JDK 1.3.1 and upwards. json-lib-x.x-jdk15 is compatible with JDK 1.5, includes support for Enums in JSONArray and JSONObject.</p><p>Download: <a rel="nofollow" href="http://sourceforge.net/projects/json-lib/files/json-lib/">json-lib.jar</a></p><p>Json-lib requires (at least) the following dependencies in your classpath:</p><ol><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-lang/commons-lang/2.5/commons-lang-2.5.jar">jakarta commons-lang 2.5</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.8.1/commons-beanutils-1.8.1.jar">jakarta commons-beanutils 1.8.0</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar">jakarta commons-collections 3.2.1</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar">jakarta commons-logging 1.1.1</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/net/sf/ezmorph/ezmorph/1.0.6/ezmorph-1.0.6.jar">ezmorph 1.0.6</a></li></ol><h3>Example</h3><pre class="brush: java; title: ; notranslate">
package net.viralpatel.java;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonMain {
	public static void main(String[] args) {

		Map&lt;String, Long&gt; map = new HashMap&lt;String, Long&gt;();
		map.put(&quot;A&quot;, 10L);
		map.put(&quot;B&quot;, 20L);
		map.put(&quot;C&quot;, 30L);

		JSONObject json = new JSONObject();
		json.accumulateAll(map);

		System.out.println(json.toString());

		List&lt;String&gt; list = new ArrayList&lt;String&gt;();
		list.add(&quot;Sunday&quot;);
		list.add(&quot;Monday&quot;);
		list.add(&quot;Tuesday&quot;);

		json.accumulate(&quot;weekdays&quot;, list);
		System.out.println(json.toString());
	}
}
</pre><p><strong>Output: </strong></p><pre class="brush: java; gutter: false; title: ; notranslate">
{&quot;A&quot;:10,&quot;B&quot;:20,&quot;C&quot;:30}
{&quot;A&quot;:10,&quot;B&quot;:20,&quot;C&quot;:30,&quot;weekdays&quot;:[&quot;Sunday&quot;,&quot;Monday&quot;,&quot;Tuesday&quot;]}
</pre><p><br/></p><h2>Using Google Gson library</h2><p>Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.</p><p>There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.</p><h3>Gson Goals</h3><ul><li>Provide simple <code>toJson()</code> and <code>fromJson()</code> methods to convert Java objects to JSON and vice-versa</li><li>Allow pre-existing unmodifiable objects to be converted to and from JSON</li><li>Extensive support of Java Generics</li><li>Allow custom representations for objects</li><li>Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)</li></ul><h3>Google Gson Example</h3><pre class="brush: java; title: ; notranslate">
import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json =
            &quot;{&quot;
                + &quot;'title': 'Computing and Information systems',&quot;
                + &quot;'id' : 1,&quot;
                + &quot;'children' : 'true',&quot;
                + &quot;'groups' : [{&quot;
                    + &quot;'title' : 'Level one CIS',&quot;
                    + &quot;'id' : 2,&quot;
                    + &quot;'children' : 'true',&quot;
                    + &quot;'groups' : [{&quot;
                        + &quot;'title' : 'Intro To Computing and Internet',&quot;
                        + &quot;'id' : 3,&quot;
                        + &quot;'children': 'false',&quot;
                        + &quot;'groups':[]&quot;
                    + &quot;}]&quot;
                + &quot;}]&quot;
            + &quot;}&quot;;

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List&lt;Data&gt; groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List&lt;Data&gt; getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List&lt;Data&gt; groups) { this.groups = groups; }

    public String toString() {
        return String.format(&quot;title:%s,id:%d,children:%s,groups:%s&quot;, title, id, children, groups);
    }
</pre><p><br/></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html" title="Tutorial: Creating Struts application in Eclipse">Tutorial: Creating Struts application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/12/calling-rpc-in-javascript-using-json-rpc-java.html" title="RPC in Javascript using JSON-RPC-Java">RPC in Javascript using JSON-RPC-Java</a></li><li><a href="http://viralpatel.net/blogs/2008/11/apostrophe-creating-problem-in-properties-file-in-java-struts.html" title="Apostrophe creating problem in properties file in java/struts">Apostrophe creating problem in properties file in java/struts</a></li><li><a href="http://viralpatel.net/blogs/2008/11/multiple-message-resource-property-file-in-struts.html" title="Multiple message resource property file in Struts">Multiple message resource property file in Struts</a></li><li><a href="http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html" title="Convert Arrays to Set in Java">Convert Arrays to Set in Java</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html" title="How To Create QR Codes in Java &#038; Servlet">How To Create QR Codes in Java &#038; Servlet</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html/feed</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Handling Session timeout &amp; other server http errors in AJAX</title><link>http://viralpatel.net/blogs/2009/02/handling-session-timeout-server-errors-http-ajax-session-ajax-session-timeout-problem.html</link> <comments>http://viralpatel.net/blogs/2009/02/handling-session-timeout-server-errors-http-ajax-session-ajax-session-timeout-problem.html#comments</comments> <pubDate>Sun, 08 Feb 2009 14:45:43 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[http error]]></category> <category><![CDATA[HTTP Request]]></category> <category><![CDATA[server error]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=783</guid> <description><![CDATA[AJAX has really changed the way we build web applications.When I surf internet today, I find almost all the websites Ajaxified in some way. Writing an AJAX application is as simple as writing simple JavaScript methods and some server side code. I have been writing AJAX codes since a long time now and believe me [...]]]></description> <content:encoded><![CDATA[<p><img class="alignright size-full wp-image-784" title="session-timeout-ajax" src="http://img.viralpatel.net/session-timeout-ajax.gif" alt="" width="260" height="219" /></p><p>AJAX has really changed the way we build web applications.When I surf internet today, I find almost all the websites Ajaxified in some way. Writing an AJAX application is as simple as writing simple JavaScript methods and some server side code.</p><p>I have been writing AJAX codes since a long time now and believe me tge most difficult part is to handle errors and exceptions. Session timeout is one of the most trivial error that one needs to consider while creating an AJAX enabled application.</p><p>Normally, we use AJAX to deliever HTML content that we put in a DIV or SPAN tag and display it on screen. But suppose the request that we sent using AJAX was generated an error due to session timeout then the session timeout screen will be shown in DIV tag. Any error generated by server let say http 404 error or http 505 can lead to display such error in our display DIV.<br /> <img class="aligncenter size-full wp-image-785" title="ajax-server-error" src="http://img.viralpatel.net/ajax-server-error.png" alt="" width="443" height="318" /></p><h2>Handle Session timeout errors</h2><p>One solution that you can use to handle the session timeout errors is using JSON or XML format as output for your AJAX requests. You have to check for session in your script, say for example if you are using JSP then probably you can do something like this:</p><pre class="brush: java; title: ; notranslate">
if(null == session || session.getAttribute(&quot;SOME_ATTR_THAT_I_PLACED_IN_SESSION&quot;)) {
	isSessionNull = true;
}
...
{
	&lt;%
	if(isSessionNull) {
		out.println(&quot;status: error&quot;);
	}
	else {
		out.println(&quot;status: success&quot;);
	}
	%&gt;
}
</pre><p>In short, create a status field in your JSON script or a status tag in your XML which will describe the status of the request.</p><p>I am looking for some more ways of checking session timeouts in AJAX. Kindly let me know if you have a good solution.</p><h2>Handle Server HTTP errors in AJAX</h2><p>HTTP errors like 404, 503 are sometimes tedious to handle using AJAX. There is a simple trick to solve this problem. First let us see simple AJAX handler function that we use to get response XML/text through AJAX.</p><pre class="brush: jscript; title: ; notranslate">
xhr.open(&quot;GET&quot;, &quot;http://someurl&quot;, true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);
...
...
function handleHttpResponse() {
	if (xhr.readyState == 4) {
		//handle response your way
		spanBodyContent.innerHTML = xhr.responseText;
	}
}
</pre><p>Normal AJAX handlers has a <strong>if</strong> to check readyState and if it is 4 (response arrived state) then we get the response from xhr.responseText or xhr.responseXML.</p><p>AJAX&#8217;s XMLHttpRequest object has attributes to check the status of your http request. You can use two attributes: status and statusText for knowing this.</p><pre class="brush: jscript; title: ; notranslate">
xhr.status
..
xhr.statusText
</pre><p>Thus by checking status attribute from your AJAX xhr object can solve your problem.</p><pre class="brush: jscript; title: ; notranslate">
xhr.open(&quot;GET&quot;, &quot;http://someurl&quot;, true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);
...
...
function handleHttpResponse() {
	if (xhr.readyState == 4) {
		try {
		if(xhr.status == 200) {
			//handle response your way
			spanBodyContent.innerHTML = xhr.responseText;
		}
		}catch(e) {//error}
	}
}
</pre><p>Thus, if status is not 200, you may not want to update your DOM with the ajax result and display some error message on your web page.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html" title="jQuery Ajax &#8211; Handling unauthenticated requests via Ajax">jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</a></li><li><a href="http://viralpatel.net/blogs/2223/wamp-server-not-getting-started-problem" title="WAMP Server not getting started problem">WAMP Server not getting started problem</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html" title="jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery">jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-push-technology-with-lightstreamer-and-comet.html" title="AJAX reloaded: Push Technology with Lightstreamer and Comet.">AJAX reloaded: Push Technology with Lightstreamer and Comet.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-cache-problem-in-ie.html" title="AJAX cache problem in IE">AJAX cache problem in IE</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html" title="AJAX Post Method example using Javascript &#038; jQuery">AJAX Post Method example using Javascript &#038; jQuery</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/02/handling-session-timeout-server-errors-http-ajax-session-ajax-session-timeout-problem.html/feed</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>AJAX reloaded: Push Technology with Lightstreamer and Comet.</title><link>http://viralpatel.net/blogs/2008/12/ajax-push-technology-with-lightstreamer-and-comet.html</link> <comments>http://viralpatel.net/blogs/2008/12/ajax-push-technology-with-lightstreamer-and-comet.html#comments</comments> <pubDate>Thu, 18 Dec 2008 13:00:57 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[comet]]></category> <category><![CDATA[cometd]]></category> <category><![CDATA[lightstreamer]]></category> <category><![CDATA[push based]]></category> <category><![CDATA[push technology]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=490</guid> <description><![CDATA[Nowadays, Web 2.0 has became a buzz word on internet. Lot of websites that you browser have that &#8220;rich&#8221; user interface with jazzy fonts and logos and ajax/javascript effects. AJAX has really changed the way we surf on internet. You see any cool web application like GMail or Google Reader, they look much like a [...]]]></description> <content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-488" title="lightstreamer-logo" src="http://img.viralpatel.net/2008/12/lightstreamer-logo.gif" alt="lightstreamer-logo" width="128" height="61" /> Nowadays, Web 2.0 has became a buzz word on internet. Lot of websites that you browser have that &#8220;rich&#8221; user interface with jazzy fonts and logos and ajax/javascript effects. AJAX has really changed the way we surf on internet. You see any cool web application like GMail or Google Reader, they look much like a desktop based application. With ajax, a new technology has arrived called &#8220;<strong>PUSH TECHNOLOGY</strong>&#8220;. A long held HTTP request allows a web server to push data to the browser without browser explicitly requesting.</p><p><a rel="nofollow" href="http://www.lightstreamer.com/index.htm" target="_new"><strong>Lightstreamer</strong></a> is product on similar line. Let us see what Lightstreamer official website has to say about it:</p><blockquote><p>Lightstreamer is a scalable and reliable Server for pushing live data to Rich Internet Applications. Based on the AJAX-Comet paradigm, it streams real-time data to any Web browser, without installing anything on the client. Both HTML and Flex applications can receive live data from Lightstreamer, as well as traditional thick clients. See below for a quick example.</p><p>Lightstreamer has been used in many mission-critical production systems, where scalability, low network impact, bandwidth management, adaptive streaming, and other advanced features, have proven fundamental.</p></blockquote><p>Lightstreamer can be used to push real time data to browser and render a graph. Trust me this looks really cool as the graph keeps on changing with time as new data gets streamed. Also you can paint a table where the values keeps on changing. For e.g. A Stock portfolio application where the current prices of stocks keep on changing and you can track real time prices. No need to hit Refresh, no need to make an Ajax call. Lightstreamer also support bandwidth control where you can actually control the bandwidth a connection can use.</p><p>Lightstreamer application has two components, a server component that is written in Java and deployed in Lightstreamer server and a client component that is written in JavaScript and run in browser. Server component keeps on pushing new data to client, which then renders it to the UI.</p><p>Ok, so Lightstreamer is soo cool.. then why I have never heard about it. ?? Well its because it is not free.. you have to pay a good amount of money to use it in production environment. There is a free copy available on Lightreamer site that you can use for evaluation. But you have to register for the free product and generate a &#8220;key&#8221; using mac address of machine where you want to run it.</p><p>There is an open source push technology framework available on internet called <a rel="nofollow" href="http://code.google.com/p/cometd/" target="_new"><strong>Cometd.</strong></a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html" title="jQuery Ajax &#8211; Handling unauthenticated requests via Ajax">jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html" title="jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery">jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2009/02/handling-session-timeout-server-errors-http-ajax-session-ajax-session-timeout-problem.html" title="Handling Session timeout &#038; other server http errors in AJAX">Handling Session timeout &#038; other server http errors in AJAX</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-cache-problem-in-ie.html" title="AJAX cache problem in IE">AJAX cache problem in IE</a></li><li><a href="http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html" title="AJAX Post Method example using Javascript &#038; jQuery">AJAX Post Method example using Javascript &#038; jQuery</a></li><li><a href="http://viralpatel.net/blogs/2008/12/calling-rpc-in-javascript-using-json-rpc-java.html" title="RPC in Javascript using JSON-RPC-Java">RPC in Javascript using JSON-RPC-Java</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/ajax-push-technology-with-lightstreamer-and-comet.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>AJAX cache problem in IE</title><link>http://viralpatel.net/blogs/2008/12/ajax-cache-problem-in-ie.html</link> <comments>http://viralpatel.net/blogs/2008/12/ajax-cache-problem-in-ie.html#comments</comments> <pubDate>Sat, 13 Dec 2008 05:47:33 +0000</pubDate> <dc:creator>Gaurav Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[cache]]></category> <category><![CDATA[cache problem]]></category> <category><![CDATA[internet explorer]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=408</guid> <description><![CDATA[Few days back I was working on a requirement where in a webpage one table was getting populated through AJAX. This table was getting refreshed every 5 mins as it was showing some real time data being processed in back end. To my surprise, the data in the table were not being refreshed and the [...]]]></description> <content:encoded><![CDATA[<p>Few days back I was working on a requirement where in a webpage one table was getting populated through <strong>AJAX</strong>. This table was getting refreshed every 5 mins as it was showing some real time data being processed in back end.</p><p>To my surprise, the data in the table were not being refreshed and the output that I was getting was not the one that I expected. Hence I tried to call the URL manually through browser. Say for example I was calling GetData.jsp from my AJAX code, so I copy/pasted this URL in browser and called it. This time I was getting the desired data in the browser.</p><p>Hence I googled the problem on internet and came to know that <strong>Internet Explorer (IE) caches the AJAX request</strong>. So if I make ajax queries with same URL, it tends to give me same result/output as IE caches the data that it gets from first query.</p><p>To overcome this problem, I used a simple hack. I appended a random number with my URL and voila, it worked.</p><p>For example, suppose below is my AJAX query. In this I am calling a URL GetData.jsp and passing one parameter <strong>requestNo</strong>.</p><pre class="brush: jscript; title: ; notranslate">
var url = &quot;GetData.jsp?requestNo=&quot; + req;
xhr.open(&quot;GET&quot;, url, true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);
</pre><p>I changed the above code into:</p><pre class="brush: jscript; title: ; notranslate">
var url = &quot;GetData.jsp?requestNo=&quot; + req  + &quot;&amp;random=&quot; + Math.random();
xhr.open(&quot;GET&quot;, url, true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);
</pre><p>Note that, I appended one more parameter with the URL which is <strong>random</strong> and assigned Math.random() with it. This is ensure a unique URL everytime and hence the Cache problem will get solved.</p><h2>jQuery load() method issue with Internet Explorer</h2><p>If you are using jQuery load() function to load content of a URL into a DIV then you may face issue in IE. Sometimes IE doesn&#8217;t load anything in the DIV.</p><pre class="brush: jscript; title: ; notranslate">
$(&quot;#mydiv&quot;).load(&quot;student.html&quot;);
</pre><p>You may want to add random url parameter to the load method so that IE doesn&#8217;t cache the content and it is properly loaded in the DIV.</p><pre class="brush: jscript; title: ; notranslate">
$(&quot;#mydiv&quot;).load(&quot;student.html&amp;random=&quot; + Math.random()*99999);
</pre><h2>Disable Cache in jQuery</h2><p>Best way to avoid caching is by disabling it through jQuery setup. Following code snippet does this:</p><pre class="brush: jscript; title: ; notranslate">
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
</pre><p>Try to use this method of disabling cache in case you using different Ajax loading techniques such as <code>.load()</code>, <code>.getJSON()</code> etc.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html" title="jQuery Ajax &#8211; Handling unauthenticated requests via Ajax">jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/09/setting-height-selectbox-combobox-ie.html" title="Setting Height of Selectbox (Combobox) in IE">Setting Height of Selectbox (Combobox) in IE</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-create-ie-specific-css-stylesheet.html" title="How To: Create an IE Specific Stylesheet">How To: Create an IE Specific Stylesheet</a></li><li><a href="http://viralpatel.net/blogs/2009/05/html-5-the-new-html-kid-on-the-block.html" title="HTML 5: The new HTML kid on the block!">HTML 5: The new HTML kid on the block!</a></li><li><a href="http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html" title="jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery">jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2009/03/javascript-multiple-selection-listbox-problem-ms-internet-explorer.html" title="Multiple Selection Listbox Javascript Problem in MS Internet Explorer">Multiple Selection Listbox Javascript Problem in MS Internet Explorer</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/ajax-cache-problem-in-ie.html/feed</wfw:commentRss> <slash:comments>21</slash:comments> </item> <item><title>AJAX Post Method example using Javascript &amp; jQuery</title><link>http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html</link> <comments>http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html#comments</comments> <pubDate>Fri, 05 Dec 2008 12:43:32 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[JQuery]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=316</guid> <description><![CDATA[Usually AJAX requests are send through GET method. This is because there are few parameters that one send while sending a request through AJAX and also it is relatively easy to create and send a GET method request. Following code is used generally to create a GET request through AJAX. Now the same code can [...]]]></description> <content:encoded><![CDATA[<p>Usually <strong>AJAX</strong> requests are send through <strong>GET method</strong>. This is because there are few parameters that one send while sending a request through AJAX and also it is relatively easy to create and send a GET method request.<br /> Following code is used generally to create a GET request through AJAX.</p><pre class="brush: jscript; title: ; notranslate">
function getXMLHttpRequestObject()
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version &gt;= 5)
    try {
      xmlhttp = new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;);
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp &amp;&amp; typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var http = new getXMLHttpRequestObject();

var url = &quot;FetchSomeData.jsp&quot;;
var parameters = &quot;name=krishna&amp;age=16&quot;;
http.open(&quot;GET&quot;, url+&quot;?&quot;+parameters, true);
http.onreadystatechange = function() { //Handler function for call back on state change.
	if(http.readyState == 4) {
		alert(http.responseText);
	}
}
http.send(null);
</pre><p>Now the same code can be re-written in order to send the request by <strong>POST method</strong>. Check the following code:</p><pre class="brush: jscript; title: ; notranslate">
var url = &quot;FetchSomeData.jsp&quot;;
var parameters = &quot;name=krishna&amp;age=16&quot;;
http.open(&quot;POST&quot;, url, true);

//Send the proper header information along with the request
http.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
http.setRequestHeader(&quot;Content-length&quot;, parameters .length);
http.setRequestHeader(&quot;Connection&quot;, &quot;close&quot;);

http.onreadystatechange = function() {//Handler function for call back on state change.
	if(http.readyState == 4) {
		alert(http.responseText);
	}
}
http.send(parameters);
</pre><p>Now compare the two code snippets. The first change that you will see is in <code>http.open()</code> method.</p><pre class="brush: jscript; title: ; notranslate">
//GET method
http.open(&quot;GET&quot;, url+&quot;?&quot;+parameters, true);

//POST method
http.open(&quot;POST&quot;, url, true);
</pre><p>In GET method, the parameters are appended with the URL and is passed in open() method, whereas in POST method the parameters are not passed with URL. The header is modified and the length of the parameter is set in it.</p><pre class="brush: jscript; title: ; notranslate">
http.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
http.setRequestHeader(&quot;Content-length&quot;, parameters .length);
http.setRequestHeader(&quot;Connection&quot;, &quot;close&quot;);
</pre><p>Hence in POST method, the parameters are send more as a form submission.</p><h3>POST method using jQuery</h3><p>Using jQuery one can easily send the request using POST method. See the following syntax.</p><pre class="brush: jscript; title: ; notranslate">
$.post(&quot;GetData.jsp&quot;,
  { name: &quot;John&quot;, time: &quot;2pm&quot; },
  function(data){
    alert(&quot;Data Loaded: &quot; + data);
  }
);
</pre><p>Here the first argument to is the script name that one needs to call. Second argument is the parameters that one needs to pass in JSON format. And finally the handler function that will be called once the request has been completed.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html" title="jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery">jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2009/04/tutorial-handle-browser-events-using-jquery-javascript-framework.html" title="Tutorial: Handle browser events using jQuery JavaScript framework">Tutorial: Handle browser events using jQuery JavaScript framework</a></li><li><a href="http://viralpatel.net/blogs/2008/12/creating-orkut-style-status-update-div-textbox-using-jquery.html" title="Creating orkut style status update div-textbox using jQuery.">Creating orkut style status update div-textbox using jQuery.</a></li><li><a href="http://viralpatel.net/blogs/2011/01/first-play-framework-gae-siena-application-tutorial-example.html" title="Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example">Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/12/jquery-ajax-handling-unauthenticated-request-ajax.html" title="jQuery Ajax &#8211; Handling unauthenticated requests via Ajax">jQuery Ajax &#8211; Handling unauthenticated requests via Ajax</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html" title="Sum HTML Textbox Values using jQuery / JavaScript">Sum HTML Textbox Values using jQuery / JavaScript</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/ajax-post-method-example-using-javascript-jquery.html/feed</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>Ajax Style File Uploading using Hidden iFrame</title><link>http://viralpatel.net/blogs/2008/11/ajax-style-file-uploading-using-hidden-iframe.html</link> <comments>http://viralpatel.net/blogs/2008/11/ajax-style-file-uploading-using-hidden-iframe.html#comments</comments> <pubDate>Tue, 18 Nov 2008 10:53:00 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[file-upload]]></category> <category><![CDATA[How-To]]></category><guid isPermaLink="false">http://localhost/wordpress/?p=122</guid> <description><![CDATA[File uploading using AJAX is not possible. AJAX doesn&#8217;t actually post forms to the server, it sends selected data to the server in the form of a POST or GET request. As javascript is not capable of grabbing the file from the users machine and sending it to the server, it&#8217;s just not possible with [...]]]></description> <content:encoded><![CDATA[<p>File uploading using AJAX is not possible. AJAX doesn&#8217;t actually post forms to the server, it sends selected data to the server in the form of a POST or GET request. As javascript is not capable of grabbing the file from the users machine and sending it to the server, it&#8217;s just not possible with AJAX. You have to resort to regular old form submit.</p><p>If you have read/seen it somewhere, then it is not through AJAX. File uploading occurs through an iframe in this case. You have to use a iframe to upload the files. So, you can use iframe to asynchronous upload (Like AJAX , but its not AJAX).</p><p>How file uploading is done in Gmail? Use following JavaScript function, if you want to achieve same functionality.</p><pre class="brush: xml; title: ; notranslate">
&lt;html&gt;

&lt;script language=&quot;Javascript&quot;&gt;
function fileUpload(form, action_url, div_id) {
    // Create the iframe...
    var iframe = document.createElement(&quot;iframe&quot;);
    iframe.setAttribute(&quot;id&quot;, &quot;upload_iframe&quot;);
    iframe.setAttribute(&quot;name&quot;, &quot;upload_iframe&quot;);
    iframe.setAttribute(&quot;width&quot;, &quot;0&quot;);
    iframe.setAttribute(&quot;height&quot;, &quot;0&quot;);
    iframe.setAttribute(&quot;border&quot;, &quot;0&quot;);
    iframe.setAttribute(&quot;style&quot;, &quot;width: 0; height: 0; border: none;&quot;);

    // Add to document...
    form.parentNode.appendChild(iframe);
    window.frames['upload_iframe'].name = &quot;upload_iframe&quot;;

    iframeId = document.getElementById(&quot;upload_iframe&quot;);

    // Add event...
    var eventHandler = function () {

            if (iframeId.detachEvent) iframeId.detachEvent(&quot;onload&quot;, eventHandler);
            else iframeId.removeEventListener(&quot;load&quot;, eventHandler, false);

            // Message from server...
            if (iframeId.contentDocument) {
                content = iframeId.contentDocument.body.innerHTML;
            } else if (iframeId.contentWindow) {
                content = iframeId.contentWindow.document.body.innerHTML;
            } else if (iframeId.document) {
                content = iframeId.document.body.innerHTML;
            }

            document.getElementById(div_id).innerHTML = content;

            // Del the iframe...
            setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
        }

    if (iframeId.addEventListener) iframeId.addEventListener(&quot;load&quot;, eventHandler, true);
    if (iframeId.attachEvent) iframeId.attachEvent(&quot;onload&quot;, eventHandler);

    // Set properties of form...
    form.setAttribute(&quot;target&quot;, &quot;upload_iframe&quot;);
    form.setAttribute(&quot;action&quot;, action_url);
    form.setAttribute(&quot;method&quot;, &quot;post&quot;);
    form.setAttribute(&quot;enctype&quot;, &quot;multipart/form-data&quot;);
    form.setAttribute(&quot;encoding&quot;, &quot;multipart/form-data&quot;);

    // Submit the form...
    form.submit();

    document.getElementById(div_id).innerHTML = &quot;Uploading...&quot;;
}
&lt;/script&gt;

&lt;!-- index.php could be any script server-side for receive uploads. --&gt;
&lt;form&gt;
&lt;input type=&quot;file&quot; name=&quot;datafile&quot; /&gt;&lt;/br&gt;
&lt;input type=&quot;button&quot; value=&quot;upload&quot;
        onClick=&quot;fileUpload(this.form,'index.php','upload'); return false;&quot; &gt;
&lt;div id=&quot;upload&quot;&gt;&lt;/div&gt;
&lt;/form&gt;

&lt;/html&gt;
</pre><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/01/javascript-array-remove-element-js-array-delete-element.html" title="JavaScript Array Remove an Element ">JavaScript Array Remove an Element </a></li><li><a href="http://viralpatel.net/blogs/2009/06/creating-dynamic-menu-planning-page-shopping-list.html" title="Creating a dynamic menu-planning page and shopping list">Creating a dynamic menu-planning page and shopping list</a></li><li><a href="http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html" title="jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery">jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li><li><a href="http://viralpatel.net/blogs/2009/01/dynamic-add-textbox-input-button-radio-element-html-javascript.html" title="Dynamically add button, textbox, input, radio elements in html form using JavaScript.">Dynamically add button, textbox, input, radio elements in html form using JavaScript.</a></li><li><a href="http://viralpatel.net/blogs/2009/01/calling-javascript-function-from-string.html" title="Calling JavaScript function from String">Calling JavaScript function from String</a></li><li><a href="http://viralpatel.net/blogs/2008/12/increase-performance-of-website-by-compressing-javascript.html" title="Increase performance of website by compressing JavaScript.">Increase performance of website by compressing JavaScript.</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/11/ajax-style-file-uploading-using-hidden-iframe.html/feed</wfw:commentRss> <slash:comments>20</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-08 21:31:21 -->
