<?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; Web 2.0</title> <atom:link href="http://viralpatel.net/blogs/category/web-20/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>Introduction to HTML5 DOMStorage API with Example</title><link>http://viralpatel.net/blogs/2010/10/introduction-html5-domstorage-api-example.html</link> <comments>http://viralpatel.net/blogs/2010/10/introduction-html5-domstorage-api-example.html#comments</comments> <pubDate>Tue, 12 Oct 2010 09:46:20 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[domstorage]]></category> <category><![CDATA[html]]></category> <category><![CDATA[html5]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2105</guid> <description><![CDATA[HTML5 is a standard for structuring and presenting content on the World Wide Web. The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash and Microsoft Silverlight. HTML5 introduces a number of new elements and attributes that reflect typical usage on modern [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2010/10/html5-image.jpg" alt="" title="html5-image" width="263" height="138" class="alignright size-full wp-image-2106" />HTML5 is a standard for structuring and presenting content on the World Wide Web. The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash and Microsoft Silverlight. HTML5 introduces a number of new elements and attributes that reflect typical usage on modern websites. Some of them are semantic replacements for common uses of generic block (<code>&lt;div&gt;</code>) and inline (<code>&lt;span&gt;</code>) elements, for example <code>&lt;nav&gt;</code> (website navigation block) and <code>&lt;footer&gt;</code> (usually referring to bottom of web page or to last lines of html code). Other elements provide new functionality through a standardized interface, such as the multimedia elements <code>&lt;audio&gt;</code> and <code>&lt;video&gt;</code>.</p><p>In addition to specifying markup, HTML5 specifies scripting application programming interfaces (APIs). Existing document object model (DOM) interfaces are extended and de facto features documented.</p><h2>What is DOM Storage?</h2><p>DOM Storage is a way to store meaningful amounts of client-side data in a persistent and secure manner.  It is a W3C draft which covers exactly how saving information on the client-side should be done. It was initially part of the HTML 5 specification, but was then taken out to be independent. Web Storage, or the somewhat confusing popular name DOM Storage, is a great way to save information for the current session and window, or for returning users.</p><p>The DOM Storage provides mechanism to securely store data in the form of key/value pairs and later retrieve to use. The main goal of this feature is to provide a comprehensive means through which interactive applications can be built (including advanced abilities, such as being able to work &#8220;offline&#8221; for extended periods of time).</p><p>DOM Storage provides a powerful way of storing and retrieving data at client side using JavaScript like APIs which are easy to use.</p><h2>Scope of DOM Storage</h2><p>DOM Storage provides different mechanism to store the client data using in-built storage objects which provides wide range of scope. For example, using DOM Storage it is possible to store data for a Session of user request, or for all the pages of a website.</p><p>DOMStorage storage mechanism is accessed by global variables of <code>window</code> object. Following are the objects available which provides different scope of data storage.</p><h3>sessionStorage</h3><p>The <code>sessionStorage</code> object can be accessed by directly referencing it by name of through <code>window.sessionStorage</code>. This is a global object (<code>sessionStorage</code>) that maintains a storage area that&#8217;s available for the duration of the page session. A page session lasts for as long as the browser is open. Opening a page in a new tab or window will cause a new session to be initiated. Note that <code>sessionStorage</code> can survive browser restart thus it is most useful for hanging on to temporary data that should be saved and restored if the browser is accidentally refreshed.</p><p><strong>Example:</strong> Save a string value &#8220;Hello, World&#8221; and display it on browser refresh.</p><pre class="brush: jscript; title: ; notranslate">
//Store the data in sessionStorage object
 sessionStorage.hello = “Hello, World!”; 

 //Retrieve the data from sessionStorage object on
 //browser refresh and display it
 window.onload = function() {
     if(sessionStorage.hello)
         alert(sessionStorage.hello);
 }
</pre><h3>localStorage</h3><p>The <code>localStorage</code> object is useful when one wants to store data that spans multiple windows and persists beyond the current session. The <code>localStorage</code> provides persistent storage area for domains.</p><p>For example: data stored at <code>localStorage['viralpatel.net']</code> can be retrieved by any script hosted at level Viralpatel.net. Similarly data stored at <code>localStorage['net']</code> can be accessed by scripts at any .net TLD level websites. Data stored as <code>localStorage['']</code> can be accessed by all the pages on all sites.</p><p><strong>Example:</strong> Following script will store a value hello at Viralpatel.net level. Thus all the scripts hosted at Viralpatel.net and its sub-domain level can both read and write the values.</p><pre class="brush: jscript; title: ; notranslate">
 //Store the data in localStorage object
 localStorage['viralpatel.net'].hello = &quot;Hello, World!&quot;;
</pre><h2>DOM Storage API</h2><p>DOM Storage objects sessionStorage and localStorage provides certain useful properties and methods API. Following are the list of such APIs.</p><ul><li><code>getItem()</code> Method – Get the value of item passed as key to the method</li><li><code>length</code> Property – Returns the length of number of items</li><li><code>remainingSpace</code> Property – Return the remaining storage space in bytes, for the storage object</li><li><code>clear()</code> Method – Remove all the key/value pairs from DOM Storage</li><li><code>key()</code> Method – Retrieves the key at specified index</li><li><code>removeItem()</code> Method – Remove the key/value pair from DOM Storage</li><li><code>setItem()</code> Method – Sets a key/value pair</li></ul><h2>Comparing HTTP Cookies with DOM Storage</h2><p>Following are few comparison points between HTTP Cookies and DOM Storage.</p><ul><li>HTTP Cookies can store limited amount of user data (e.g. 4KB) where as modern browser such as IE 8 supports up to 10MB of data being stored with DOM Storage</li><li>Cookies limits the accessibility of data to a certain domain name or a URL path where as DOM Storage can limit the access to a certain domain name, or to domain TLD (like .org) or for given user session.</li><li>The keys stored with HTTP Cookies can be retrieved by using APIs. It is possible to iterate through all the key/value pairs in HTTP Cookies. Whereas in DOM Storage it is not possible to iterate through keys. Data cannot be retrieved unless key is known.</li><li>Data stored as HTTP Cookies can be retrieved at Server as this data is passed with request. Whereas the DOMStorage is more of client data and is not possible to retrieve it directly at server side.</li></ul><h2>Web Browser Support</h2><p>Currently modern browsers such as Firefox 3.5, Internet Explorer 8 and Safari 4 fully support the DOM Storage specification. Following are the list of browsers and their corresponding values such as Storage size, Support, Survive Browser Restart.</p><style>.adtable{border:1px
solid #eee;border-collapse:collapse;width:550px;font-family:Calibri}.adtable
th{border:1px
solid #888;height:30px;background-color:#3275A8;text-align:center;vertical-align:middle;color:white}.adtable
tr{border:1px
solid #888}.adtable
tr.odd{background-color:#eee}.adtable
td{padding:2px;border:1px
solid #888}</style><table class="adtable"><tr><th>Browser</th><th>Storage Size</th><th>Storage Support</th><th>Survives Browser Restart</th></tr><tr><td>Firefox 2</td><td>5 MB</td><td>Yes</td><td>No</td></tr><tr class="odd"><td>Firefox 3</td><td>5 MB</td><td>Yes</td><td>No</td></tr><tr><td>Firefox 3.5</td><td>5 MB</td><td>Yes</td><td>Yes</td></tr><tr class="odd"><td>Safari 3</td><td>-</td><td>No</td><td>No</td></tr><tr><td>Safari 4</td><td>5 MB</td><td>Yes</td><td>Yes</td></tr><tr class="odd"><td>Chrome 2</td><td>-</td><td>No</td><td>No</td></tr><tr><td>IE 8</td><td>10 MB</td><td>Yes</td><td>Yes</td></tr><tr class="odd"><td>Opera 10</td><td>-</td><td>No</td><td>No</td></tr></table><h2>Demo Application</h2><p>Let us demonstrate the use of DOMStorage API and create a demo application.</p><h3>Application Requirement</h3><p>Application has a form called Client Form with some input elements. The requirement is to persist the values of the form in case the page is accidentally refreshed and restore the values back.</p><h3>User Interface</h3><p>Demo application will have a simple input form to enter Client information. The form will have few input fields to capture user input. In case of accidental refresh of the webpage the values should be persevered in the form.<br /> <img src="http://img.viralpatel.net/2010/10/html5-domstorage-api-demo.png" alt="html5-domstorage-api-demo" title="html5-domstorage-api-demo" width="359" height="394" class="aligncenter size-full wp-image-2107" /></p><h3>Source Code</h3><p>Following is the HTML Source code of web page containing Client Form:</p><pre class="brush: xml; title: ; notranslate">
&lt;HTML&gt;
  &lt;HEAD&gt;
    &lt;TITLE&gt;DOMStorage - Sample Application
    &lt;/TITLE&gt;
  &lt;/HEAD&gt;
  &lt;BODY&gt;
    &lt;H2&gt;Client Form
    &lt;/H2&gt;
    &lt;br/&gt;
    &lt;form name=&quot;clientForm&quot; id=&quot;clientForm&quot;&gt;
      &lt;table&gt;
        &lt;tr&gt;
          &lt;td&gt;First Name
          &lt;/td&gt;
          &lt;td&gt;
            &lt;input type=&quot;text&quot; name=&quot;firstname&quot;/&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Last Name
          &lt;/td&gt;
          &lt;td&gt;
            &lt;input type=&quot;text&quot; name=&quot;lastname&quot;/&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Date of Birth
          &lt;/td&gt;
          &lt;td&gt;
            &lt;input type=&quot;text&quot; name=&quot;dob&quot;/&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Gender
          &lt;/td&gt;
          &lt;td&gt;
            &lt;input name=&quot;gender&quot; type=&quot;radio&quot; value=&quot;M&quot;&gt;Male
          &lt;/input&gt;
          &lt;input name=&quot;gender&quot; type=&quot;radio&quot; value=&quot;F&quot;&gt;Female
        &lt;/input&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;Designation
          &lt;/td&gt;
          &lt;td&gt;
            &lt;select name=&quot;designation&quot;&gt;
              &lt;option value=&quot;0&quot;&gt;Software Engineer
              &lt;/option&gt;
              &lt;option value=&quot;1&quot;&gt;Sr. Software Engineer
              &lt;/option&gt;
              &lt;option value=&quot;2&quot;&gt;Technical Architect
              &lt;/option&gt;
            &lt;/select&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td colspan=&quot;2&quot;&gt;
            &lt;br/&gt;
            &lt;input name=&quot;submit&quot; type=&quot;button&quot; value=&quot;Submit&quot;/&gt;
            &lt;input name=&quot;reset&quot; type=&quot;reset&quot; value=&quot;Reset&quot;/&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/form&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;domstorage-persist.js&quot;&gt;&lt;/script&gt;

  &lt;/BODY&gt;
&lt;/HTML&gt;
</pre><p>Following is JavaScript code (content of domstorage-persist.js)</p><pre class="brush: jscript; title: ; notranslate">
/**
 * Filename: domstorage-persist.js
 * Author: viralpatel.net
 * Description: HTML code independent form persistent
 * Usage:  persist(&lt;form object&gt;);
 */

function persist(form) {

/*
   * In case of page refresh,
   * store the values of form to DOMStorage
   */
    window.onbeforeunload = function () {
        var str = serialize(form);

        try {
            sessionStorage[form.name] = str;
        } catch (e) {}
    }

/*
   * If the form was refreshed and old values are available,
   * restore the old values in form
   */
    window.onload = function () {
        try {
            if (sessionStorage[form.name]) {
                var obj = eval(&quot;(&quot; + sessionStorage[form.name] + &quot;)&quot;);
                for (var i = 0; i &lt; obj.elements.length - 1; i++) {
                    var elementName = obj.elements[i].name;
                    document.forms[obj.formName].elements[obj.elements[i].name].value = obj.elements[i].value;
                }

            }
        } catch (e) {}
    }
}

/*
 * Convert form elements into JSON String
 */

function serialize(form) {
    var serialized = '{ &quot;formName&quot;:&quot;' + form.name + '&quot;, &quot;elements&quot;: [';
    for (var i = 0; i &lt; form.elements.length; i++) {

        serialized += '{';
        serialized += '&quot;name&quot;:&quot;' + form[i].name + '&quot;,';
        serialized += '&quot;value&quot;:&quot;' + form[i].value + '&quot;';
        serialized += '},';
    }
    serialized += '{&quot;name&quot;:0, &quot;value&quot;:0}';
    serialized += '] }';
    return serialized;
}

/*
 * Make the Client Form persistable.
 * i.e. Persist its values in case of page refresh
 */
persist(document.clientForm);
</pre><h2>References</h2><ul><li>W3C: Web Storage draft standard (<a rel="nofollow" target="_blank" href="http://dev.w3.org/html5/webstorage/">http://dev.w3.org/html5/webstorage/</a>)</li><li>Mozilla Developer Center: DOM Storage (<a rel="nofollow" target="_blank" href="https://developer.mozilla.org/En/DOM:Storage#Description">https://developer.mozilla.org/En/DOM:Storage#Description</a>)</li><li>MSDN: Introduction to DOM Storage ( <a rel="nofollow" target="_blank" href="http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx#_dom">http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx#_dom</a>)</li></ul><h2>Further Reading</h2><p>The given article focuses on the latest mechanism of DOMStorage being standardized by World Wide Web Consortium (W3C) as part of HTML5. There are few other similar technologies available which can be leveraged to store offline data in browser. Users who are interested in browser based storage are highly advisable to read about following technologies.</p><ul><li>HTTP Cookies (<a rel="nofollow" target="_blank" href="http://www.microsoft.com/info/cookies.mspx">http://www.microsoft.com/info/cookies.mspx</a>)</li><li>DOMCached &#8211; A memcached like caching system for JavaScript using DOM storage (<a rel="nofollow" target="_blank" href="http://www.domcached.com">http://www.domcached.com</a>)</li><li>Google Gears (<a rel="nofollow" target="_blank" href="http://gears.google.com/">http://gears.google.com/</a>)</li><li>Adobe Flash – Local Shared Objects (<a rel="nofollow" target="_blank" href="http://www.adobe.com/products/flashplayer/articles/lso/">http://www.adobe.com/products/flashplayer/articles/lso/</a>)</li></ul><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><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/2010/06/facebook-facts-you-didnt-know.html" title="Facebook: Facts you probably didnt know">Facebook: Facts you probably didnt know</a></li><li><a href="http://viralpatel.net/blogs/2010/01/oembed-open-format-web-developers.html" title="oEmbed: An Open Format Every Developer Should Know About">oEmbed: An Open Format Every Developer Should Know About</a></li><li><a href="http://viralpatel.net/blogs/2009/11/disable-back-button-browser-javascript.html" title="Disable Back Button in Browser using JavaScript">Disable Back Button in Browser using JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2009/09/gartners-hype-cycle-special-report-2009.html" title=" Gartner&#8217;s Hype Cycle Special Report for 2009"> Gartner&#8217;s Hype Cycle Special Report for 2009</a></li><li><a href="http://viralpatel.net/blogs/2009/05/gravatar-manage-your-user-avatars-for-free.html" title="Gravatar: Manage your user avatars for free">Gravatar: Manage your user avatars for free</a></li><li><a href="http://viralpatel.net/blogs/2009/05/web-30-is-around-the-corner.html" title="Web 3.0 is around the corner !">Web 3.0 is around the corner !</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/10/introduction-html5-domstorage-api-example.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Facebook: Facts you probably didnt know</title><link>http://viralpatel.net/blogs/2010/06/facebook-facts-you-didnt-know.html</link> <comments>http://viralpatel.net/blogs/2010/06/facebook-facts-you-didnt-know.html#comments</comments> <pubDate>Thu, 24 Jun 2010 07:41:09 +0000</pubDate> <dc:creator>Sneha</dc:creator> <category><![CDATA[News]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[facebook]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2072</guid> <description><![CDATA[Have you ever wondered how Facebook has grown rapidly in these recent years! Here is a wonderful info about Facebook. Image courtesy: onlineschools.org Related PostsFacebook Style Scroll Fixed Header in JQueryIntroduction to HTML5 DOMStorage API with ExampleoEmbed: An Open Format Every Developer Should Know About Gartner&#8217;s Hype Cycle Special Report for 2009What if the Facebook [...]]]></description> <content:encoded><![CDATA[<p>Have you ever wondered how Facebook has grown rapidly in these recent years! Here is a wonderful info about Facebook.<br /> <img src="http://img.viralpatel.net/2010/06/everything-about-facebook..jpg" alt="everything-about-facebook" title="everything-about-facebook" width="640" height="3200" class="aligncenter size-full wp-image-2073" /><br /> Image courtesy: <a rel="nofollow" target="_new" href="http://onlineschools.org">onlineschools.org</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><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/2010/10/introduction-html5-domstorage-api-example.html" title="Introduction to HTML5 DOMStorage API with Example">Introduction to HTML5 DOMStorage API with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/01/oembed-open-format-web-developers.html" title="oEmbed: An Open Format Every Developer Should Know About">oEmbed: An Open Format Every Developer Should Know About</a></li><li><a href="http://viralpatel.net/blogs/2009/09/gartners-hype-cycle-special-report-2009.html" title=" Gartner&#8217;s Hype Cycle Special Report for 2009"> Gartner&#8217;s Hype Cycle Special Report for 2009</a></li><li><a href="http://viralpatel.net/blogs/2009/08/what-if-facebook-is-country.html" title="What if the Facebook is a Country?">What if the Facebook is a Country?</a></li><li><a href="http://viralpatel.net/blogs/2009/08/pillows-try-social-media-pillow.html" title="Pillows for you: Try these Social Media Pillow">Pillows for you: Try these Social Media Pillow</a></li><li><a href="http://viralpatel.net/blogs/2009/07/precrime-minority-report-real-facebook-england.html" title="Pre-crime &#038; Minority Report turns real through Facebook in England">Pre-crime &#038; Minority Report turns real through Facebook in England</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/06/facebook-facts-you-didnt-know.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>oEmbed: An Open Format Every Developer Should Know About</title><link>http://viralpatel.net/blogs/2010/01/oembed-open-format-web-developers.html</link> <comments>http://viralpatel.net/blogs/2010/01/oembed-open-format-web-developers.html#comments</comments> <pubDate>Tue, 26 Jan 2010 09:24:36 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[JQuery]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[oembed]]></category> <category><![CDATA[youtube]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2000</guid> <description><![CDATA[Most of the internet users spend their online time in creating and sharing content on internet. Sharing has became one of the most popular activity of internet users. This is attributed to formats like RSS and services like Twitter, Facebook etc. that allows user to share content with each other. oEmbed addresses the important task [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2010/01/oembed-all-service.png" alt="oembed-all-service" title="oembed-all-service" width="352" height="180" class="aligncenter size-full wp-image-2002" /><br /> Most of the internet users spend their online time in creating and sharing content on internet. Sharing has became one of the most popular activity of internet users. This is attributed to formats like RSS and services like Twitter, Facebook etc. that allows user to share content with each other.</p><p>oEmbed addresses the important task of sharing and embedding information anywhere on internet. It allows developers to build applications that can easily access data from vast number of websites like youtube, flickr, google video, wordpress, wikipedia and many many more.</p><p>So what&#8217;s oEmbed? Well if you go by the definition on oEmbed&#8217;s <a rel="nfollow" target="_blank" href="http://www.oembed.com/">official website</a>:</p><blockquote><p>oEmbed is a format for allowing an embedded representation of a URL on third party sites. The simple API allows a website to display embedded content (such as photos or videos) when a user posts a link to that resource, without having to parse the resource directly.</p></blockquote><p>The best example of oEmbed can be Facebook&#8217;s status update feature. When you paste a youtube movie link in Facebook&#8217;s status bar, it automatically identify the link content as youtube movie and embed it in the status. Similarly you can paste any kind of content link: Flickr, Wikipedia etc.</p><p><img src="http://img.viralpatel.net/2010/01/facebook-oembed.png" alt="facebook-oembed" title="facebook-oembed" width="564" height="364" class="aligncenter size-full wp-image-2001" /></p><h2>Basics of oEmbed</h2><p>In this document I will use two terms very often, <strong>consumer</strong> and <strong>provider</strong>. Consumer is the client who wants to convert a link into embedded content. And Provider is one who get the request and send the oembed response. For example, if you paste a youtube URL in Facebook&#8217;s status update, Facebook will be the consumer and Youtube will be the provider.</p><p>A consumer who wants to convert a link into content will make an HTTP request like:</p><pre class="brush: xml; title: ; notranslate">

http://www.flickr.com/services/oembed/?url=http%3A//www.flickr.com/photos/bees/2341623661/
</pre><p>and the provider, in this case Flickr will send response in JSON format:</p><pre class="brush: xml; title: ; notranslate">
{
	&quot;version&quot;: &quot;1.0&quot;,
	&quot;type&quot;: &quot;photo&quot;,
	&quot;width&quot;: 240,
	&quot;height&quot;: 160,
	&quot;title&quot;: &quot;ZB8T0193&quot;,
	&quot;url&quot;: &quot;http://farm4.static.flickr.com/3123/2341623661_7c99f48bbf_m.jpg&quot;,
	&quot;author_name&quot;: &quot;Bees&quot;,
	&quot;author_url&quot;: &quot;http://www.flickr.com/photos/bees/&quot;,
	&quot;provider_name&quot;: &quot;Flickr&quot;,
	&quot;provider_url&quot;: &quot;http://www.flickr.com/&quot;
}
</pre><p><strong>Youtube example:</strong><br /> Request URL:</p><pre class="brush: xml; title: ; notranslate">

http://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3DM3r2XDceM6A&#038;format=json
</pre><p>Response:</p><pre class="brush: xml; title: ; notranslate">
{
	&quot;version&quot;: &quot;1.0&quot;,
	&quot;type&quot;: &quot;video&quot;,
	&quot;provider_name&quot;: &quot;YouTube&quot;,
	&quot;provider_url&quot;: &quot;http://youtube.com/&quot;,
	&quot;width&quot;: 425,
	&quot;height&quot;: 344,
	&quot;title&quot;: &quot;Amazing Nintendo Facts&quot;,
	&quot;author_name&quot;: &quot;ZackScott&quot;,
	&quot;author_url&quot;: &quot;http://www.youtube.com/user/ZackScott&quot;,
	&quot;html&quot;:
		&quot;&lt;object width=\&quot;425\&quot; height=\&quot;344\&quot;&gt;
			&lt;param name=\&quot;movie\&quot; value=\&quot;http://www.youtube.com/v/M3r2XDceM6A&amp;fs=1\&quot;&gt;&lt;/param&gt;
			&lt;param name=\&quot;allowFullScreen\&quot; value=\&quot;true\&quot;&gt;&lt;/param&gt;
			&lt;param name=\&quot;allowscriptaccess\&quot; value=\&quot;always\&quot;&gt;&lt;/param&gt;
			&lt;embed src=\&quot;http://www.youtube.com/v/M3r2XDceM6A&amp;fs=1\&quot;
				type=\&quot;application/x-shockwave-flash\&quot; width=\&quot;425\&quot; height=\&quot;344\&quot;
				allowscriptaccess=\&quot;always\&quot; allowfullscreen=\&quot;true\&quot;&gt;&lt;/embed&gt;
		&lt;/object&gt;&quot;,
}</pre><p>Once the consumer get the response, all it has to do is to utilize the content and embed it in the page.</p><h3>Request Format</h3><p>The consumer who is requesting for the embed content must follow some basic rules while sending request. Requests sent to the API must be HTTP GET requests, with all arguments sent as query parameters. All arguments must be urlencoded.<br /> Following are the request parameters:</p><ul><li><strong>url</strong> (required): This is the URL for which embedded content is requested</li><li><strong>maxwidth</strong> (optional): An optional parameter for maxwidth can be passed. Some of the content provider who support this param will send the response content accordingly. For example, Flickr may set the maxwidth of image.</li><li><strong>maxheight</strong> (optional): Similar to maxwidth, maxheight is an optional param.</li><li><strong>format</strong> (optional): By default the content provider&#8217;s response is in JSON. But consumer may want the response in other formats like XML. This parameter will determine is response format</li></ul><h3>Response Format</h3><p>The provider who sends the response back to consumer may send it with following parameters.</p><ul><li><strong>type</strong> (required): The resource type. Valid values, along with value-specific parameters, are described below.</li><li><strong>version</strong> (required): The oEmbed version number. This must be 1.0.</li><li><strong>title</strong> (optional): A text title, describing the resource.</li><li><strong>author_name</strong> (optional): The name of the author/owner of the resource.</li><li><strong>author_url</strong> (optional): A URL for the author/owner of the resource.</li><li><strong>provider_name</strong> (optional): The name of the resource provider.</li><li><strong>provider_url</strong> (optional): The url of the resource provider.</li><li><strong>cache_age</strong> (optional): The suggested cache lifetime for this resource, in seconds. Consumers may choose to use this value or not.</li><li><strong>thumbnail_url</strong> (optional): A URL to a thumbnail image representing the resource. The thumbnail must respect any maxwidth and maxheight parameters. If this paramater is present, thumbnail_width and thumbnail_height must also be present.</li><li><strong>thumbnail_width</strong> (optional): The width of the optional thumbnail. If this paramater is present, thumbnail_url and thumbnail_height must also be present.</li><li><strong>thumbnail_height</strong> (optional): The height of the optional thumbnail. If this paramater is present, thumbnail_url and thumbnail_width must also be present.</li></ul><p>The provider may wants to add more attributes to the response.</p><h2>Letting People Know You Support oEmbed</h2><p>The oEmbed providers can make their service discoverable by adding following element in HEAD for the HTML document.</p><pre class="brush: xml; title: ; notranslate">
&lt;link rel=&quot;alternate&quot; type=&quot;application/json+oembed&quot;
	href=&quot;http://flickr.com/services/oembed?url=http%3A//flickr.com/photos/bees/2362225867/&amp;format=json&quot;
	title=&quot;Bacon Lollys oEmbed Profile&quot; /&gt;
&lt;link rel=&quot;alternate&quot; type=&quot;text/xml+oembed&quot;
	href=&quot;http://flickr.com/services/oembed?url=http%3A//flickr.com/photos/bees/2362225867/&amp;format=xml&quot;
	title=&quot;Bacon Lollys oEmbed Profile&quot; /&gt;
</pre><p>The URLs contained within the href attribute should be the full oEmebed endpoint plus URL and any needed format parameter. No other request parameters should be included in this URL.</p><p>The type attribute must contain either application/json+oembed for JSON responses, or text/xml+oembed for XML.</p><h2>oEmbed Demo with jQuery</h2><p>Integrating oEmbed support in your application using jQuery is very easy using <a rel="nofollow" target="_blank" href="http://code.google.com/p/jquery-oembed/">jQuery oEmbed plugin</a>. Following is the source code the of demo.<br /> <b>The HTML Code</b></p><pre class="brush: xml; title: ; notranslate">
Content URL:
&lt;input type=&quot;text&quot; id=&quot;update&quot;/&gt;&lt;button id=&quot;btn&quot;&gt;Get&lt;/button&gt;
&lt;div id=&quot;embed&quot;&gt;&lt;/div&gt;
</pre><p><b>The jQuery Code</b></p><pre class="brush: jscript; title: ; notranslate">
$(function(){
	$('#btn').click(function() {
		$(&quot;#embed&quot;).oembed($('#update').val());
	});
});
</pre><p>Don&#8217;t forget to include jquery library and jquery oembed javascript in the demo.<br /> <b>The Demo</b><br /> Enter any oEmbed supporting URL (Youtube video link or Flickr link <strong>http://www.flickr.com/photos/stuckincustoms/2035748576/</strong>) in below textbox and press Get.<br /> <iframe src="http://viralpatel.net/blogs/demo/oembed/demo.html" width="100%" height="300px"></iframe><br /> (<a target="_blank" href="http://viralpatel.net/blogs/demo/oembed/demo.html">demo link</a>)</p><h3>oEmbed in PHP</h3><p>There is a small PHP library that can be used to integrate oEmbed support in PHP. <a rel="nofollow" target="_blank" href="http://code.google.com/p/php-oembed/">oEmbed-PHP</a> is a library that provides OEmbed compatible interface for javascript and PHP clients to consume. It can deal with OEmbed providers by acting as a proxy, and it has a plugin system where you can add your own embed-providers.<br /> Import this small PHP library and directly use it in your application.</p><pre class="brush: php; title: ; notranslate">
  $manager = ProviderManager::getInstance();
  $obj=$manager-&gt;provide(&quot;http://www.youtube.com/watch? v=EQqJSAOOmGI&quot;,&quot;object&quot;);
  $html=$obj-&gt;renderClass();
</pre><h2>oEmbed for other languages</h2><p><b>Perl</b><br /> Web-oEmbed (<a rel="nofollow" target="_blank" href="http://search.cpan.org/~miyagawa/Web-oEmbed/">http://search.cpan.org/~miyagawa/Web-oEmbed/</a>)</p><p><b>Ruby</b><br /> oembed_links (<a rel="nofollow" target="_blank" href="http://github.com/netshade/oembed_links">http://github.com/netshade/oembed_links</a>)</p><p><b>Python</b><br /> Python oEmbed (<a rel="nofollow" target="_blank" href="http://code.google.com/p/python-oembed/">http://code.google.com/p/python-oembed/</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/10/introduction-html5-domstorage-api-example.html" title="Introduction to HTML5 DOMStorage API with Example">Introduction to HTML5 DOMStorage API with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/06/facebook-facts-you-didnt-know.html" title="Facebook: Facts you probably didnt know">Facebook: Facts you probably didnt know</a></li><li><a href="http://viralpatel.net/blogs/2009/09/gartners-hype-cycle-special-report-2009.html" title=" Gartner&#8217;s Hype Cycle Special Report for 2009"> Gartner&#8217;s Hype Cycle Special Report for 2009</a></li><li><a href="http://viralpatel.net/blogs/2009/07/youtube-experimenting-3d-videos.html" title="YouTube Experimenting with 3D videos!">YouTube Experimenting with 3D videos!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/gravatar-manage-your-user-avatars-for-free.html" title="Gravatar: Manage your user avatars for free">Gravatar: Manage your user avatars for free</a></li><li><a href="http://viralpatel.net/blogs/2009/05/web-30-is-around-the-corner.html" title="Web 3.0 is around the corner !">Web 3.0 is around the corner !</a></li><li><a href="http://viralpatel.net/blogs/2009/05/capture-website-screenshot-screenshot-capture-utilities.html" title="Capture Website Screenshot with screenshot capture utilities">Capture Website Screenshot with screenshot capture utilities</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/01/oembed-open-format-web-developers.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Create your own Search Engine(Interface) using Google Custom Search API</title><link>http://viralpatel.net/blogs/2009/10/create-search-engine-google-custom-search-api.html</link> <comments>http://viralpatel.net/blogs/2009/10/create-search-engine-google-custom-search-api.html#comments</comments> <pubDate>Thu, 29 Oct 2009 15:36:22 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[google]]></category> <category><![CDATA[google custom search]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1879</guid> <description><![CDATA[Google Custom Search API are wonderful tools to create some awesome search engine like tools. Also if you want to add a search option to your website and customize the look and feel of your search results, Google Custom Search API serve best to you. I have created a Real Time Search engine (I call [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/10/google-api-real-time-search.png" alt="google-api-real-time-search" title="google-api-real-time-search" width="462" height="144" class="aligncenter size-full wp-image-1881" /><br /> Google Custom Search API are wonderful tools to create some awesome search engine like tools. Also if you want to add a search option to your website and customize the look and feel of your search results, Google Custom Search API serve best to you.</p><p>I have created a Real Time Search engine (I call it real time as it search as you type). I am really impressed by the speed/response of Google Search API.<br /><center></p><h3><a target="_new" href="http://viralpatel.net/realtime/">DEMO</a></h3><p></center><br /> <img src="http://img.viralpatel.net/2009/10/google-search-technology.PNG" alt="google-search-technology" title="google-search-technology" width="473" height="330" class="aligncenter size-full wp-image-1880" /></p><p><center></p><h3><a target="_new" href="http://viralpatel.net/realtime/">DEMO</a></h3><p></center></p><h2>The Code</h2><p>I will show the code for one of the search api that I implemented in demo page. Let us see how to implement Web Search API.</p><h3>Step 1: Generate Google Search API Key and Include JavaScript</h3><p>In order to use Google Search API, you have to first generate a Key for you. Go to following page and signup your self for the Key.<br /> <a target="_new" href="http://code.google.com/apis/ajaxsearch/signup.html">Sign up for Google API Key</a></p><p>Next step is to include the Google Search API javascript. Don&#8217;t forget to mention your key in the below code.</p><pre class="brush: jscript; title: ; notranslate">
&lt;script src=&quot;http://www.google.com/jsapi?key=YOURKEY&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
	google.load('search', '1');
&lt;/script&gt;
</pre><h3>Step 2: Add HTML Container for Web Search</h3><p>We will create a textbox and a button that will take input for search. And a DIV that will be populated by results:</p><pre class="brush: xml; title: ; notranslate">
&lt;input type=&quot;text&quot; title=&quot;Real Time Search&quot; name=&quot;searchbox&quot;/&gt;
&lt;input type=&quot;button&quot; id=&quot;searchbtn&quot; value=&quot;Search&quot; onclick=&quot;search(searchbox.value)&quot;/&gt;

&lt;div class=&quot;data&quot; id=&quot;web-content&quot;&gt;&lt;/div&gt;
</pre><p>When user will write a query and push Search button, a request will be made to Google Search using Custom Search API and the results are fetched. These results are then copied into the DIV.</p><h3>Step 3: JavaScript to call Google Search API</h3><p>We will use following JavaScript to call the Google Search API and copy the results in our container DIV.<br /> The code in plain english is:<br /> 1. Create an object to connect Google Web search using class <code>google.search.WebSearch</code>.<br /> 2. Set a callback function that will get call once the results for the search are fetched.<br /> 3. Call the <code>execute()</code> method with search query as argument.<br /> 4. In callback function, iterate through the results and copy it to container DIV.</p><pre class="brush: jscript; title: ; notranslate">
var webSearch;
webSearch = new google.search.WebSearch();
webSearch.setSearchCompleteCallback(this, webSearchComplete, [webSearch]);

function webSearchComplete (searcher, searchNum) {
	var contentDiv = document.getElementById('web-content');
	contentDiv.innerHTML = '';
    var results = searcher.results;

    var newResultsDiv = document.createElement('div');
    newResultsDiv.id = 'web-content';
    for (var i = 0; i &lt; results.length; i++) {
      var result = results[i];

	  var resultHTML = '&lt;div&gt;';
      resultHTML += '&lt;a href=&quot;' + result.unescapedUrl + '&quot; target=&quot;_blank&quot;&gt;&lt;b&gt;' +
                        result.titleNoFormatting + '&lt;/b&gt;&lt;/a&gt;&lt;br/&gt;' +
                        result.content +
                        '&lt;div/&gt;';
      newResultsDiv.innerHTML += resultHTML;
    }
    contentDiv.appendChild(newResultsDiv);
}

function search(query) {
	webSearch.execute(query);
}
</pre><h3><a target="_new" href="http://viralpatel.net/realtime/">Click for Online Demo</a></h3><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/03/chrome-experiment-googles-new-site-showcase-chrome-javascript.html" title="Chrome Experiment: Google&#8217;s new site to showcase Chrome and JavaScript">Chrome Experiment: Google&#8217;s new site to showcase Chrome and JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html" title="STOP SOPA JQuery Plugin">STOP SOPA JQuery Plugin</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html" title="Create ZIP Files in JavaScript">Create ZIP Files in JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2011/07/google-plus-homepage-redirect.html" title="Redirect your homepage /+ URL to your Google + profile">Redirect your homepage /+ URL to your Google + profile</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/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/2010/01/google-takes-china-stop-censoring.html" title="Google Takes on China; Will Stop Censoring Results">Google Takes on China; Will Stop Censoring Results</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/10/create-search-engine-google-custom-search-api.html/feed</wfw:commentRss> <slash:comments>19</slash:comments> </item> <item><title>What if the Facebook is a Country?</title><link>http://viralpatel.net/blogs/2009/08/what-if-facebook-is-country.html</link> <comments>http://viralpatel.net/blogs/2009/08/what-if-facebook-is-country.html#comments</comments> <pubDate>Fri, 28 Aug 2009 13:09:41 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Fun]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[facebook]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1703</guid> <description><![CDATA[Facebook has made its way from a small social network website running in a university to a giant mammoth of 250 Million users worldwide. Buzzpoint, a social media marketing firm based out of Los Angeles, has put together an impressive visualization that shows off just how large Facebook has grown. The comparison has been done [...]]]></description> <content:encoded><![CDATA[<p>Facebook has made its way from a small social network website running in a university to a giant mammoth of 250 Million users worldwide. <a rel="nofollow" href="http://www.buzzpoint.com/">Buzzpoint</a>, a social media marketing firm based out of Los Angeles, has put together an impressive visualization that shows off just how large Facebook has grown. The comparison has been done with different Countries in terms of population and facebook users.</p><h2>Facebook as 4th largest country in world in terms of population</h2><p><img alt="Faceb" src="http://cache0.techcrunch.com/wp-content/uploads/2009/08/fbfigures1.png" class="aligncenter" width="632" height="402" /></p><h2>Top five countries with most facebook users</h2><p><img alt="five countries with most facebook users" src="http://cache0.techcrunch.com/wp-content/uploads/2009/08/fbstats2.png" class="aligncenter" width="630" height="383" /></p><h2>Facebook as terms of % of populations</h2><p><img alt="Facebook as terms of % of populations" src="http://cache0.techcrunch.com/wp-content/uploads/2009/08/fbstats3.png" class="aligncenter" width="632" height="420" /></p><p>Image Courtesy: <a rel="nfollow" href="http://www.techcrunch.com/2009/08/27/a-look-at-facebooks-reach-worldwide/">Techcrunch</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/08/pillows-try-social-media-pillow.html" title="Pillows for you: Try these Social Media Pillow">Pillows for you: Try these Social Media Pillow</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/2010/06/facebook-facts-you-didnt-know.html" title="Facebook: Facts you probably didnt know">Facebook: Facts you probably didnt know</a></li><li><a href="http://viralpatel.net/blogs/2010/01/google-first-doodle-newton-anniversary.html" title="Google&#8217;s First Animated Doodle for Newton&#8217;s Anniversary">Google&#8217;s First Animated Doodle for Newton&#8217;s Anniversary</a></li><li><a href="http://viralpatel.net/blogs/2009/11/google-wave-fail-whale.html" title="Google Wave has its own Fail Whale">Google Wave has its own Fail Whale</a></li><li><a href="http://viralpatel.net/blogs/2009/08/if-twitter-consisted-of-100-people.html" title="If Twitter Consisted of 100 People!">If Twitter Consisted of 100 People!</a></li><li><a href="http://viralpatel.net/blogs/2009/07/precrime-minority-report-real-facebook-england.html" title="Pre-crime &#038; Minority Report turns real through Facebook in England">Pre-crime &#038; Minority Report turns real through Facebook in England</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/08/what-if-facebook-is-country.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Display Twitter User Image on your Blog/Website in 2 Minutes</title><link>http://viralpatel.net/blogs/2009/08/display-twitter-user-image-on-your-blogwebsite-in-2-minutes.html</link> <comments>http://viralpatel.net/blogs/2009/08/display-twitter-user-image-on-your-blogwebsite-in-2-minutes.html#comments</comments> <pubDate>Tue, 18 Aug 2009 08:01:08 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[avatar]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[twitter]]></category> <category><![CDATA[twitter api]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1667</guid> <description><![CDATA[Twitter API has became a powerful way of getting information about a twitter user and her activities. In my previous tutorial we saw how to create a simple twitter reader in 5 minutes. Let us see how to get the User Image (or Avatar) from Twitter and display it anywhere you want. So how can [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/08/twitter-avatars.png" alt="twitter-avatar" title="twitter-avatars" width="222" height="214" class="alignleft size-full wp-image-1671" />Twitter API has became a powerful way of getting information about a twitter user and her activities.  In my previous tutorial we saw how to create a simple <a href="http://viralpatel.net/blogs/2009/08/creating-simple-twitter-reader-client-5-minutes.html">twitter reader</a> in 5 minutes. Let us see how to get the User Image (or Avatar) from Twitter and display it anywhere you want.</p><p>So how can I display the Twitter User Image on my Blog in 2 minutes??? All you have to do is to add following IMAGE tag where you want to display Twitter&#8217;s User Image and that&#8217;s it.</p><pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;http://viralpatel.net/blogs/demo/twitter-image.php?user=&lt;TWITTER_USER&gt;&quot; /&gt;
</pre><p>In above code, just put the TWITTER_USER name of person whos image you want to display.<br /> For example, for me the above URL will be:</p><p><img src="http://viralpatel.net/blogs/demo/twitter-image.php?user=virp" /></p><pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;http://viralpatel.net/blogs/demo/twitter-image.php?user=virp&quot; /&gt;
</pre><p>One of the use of this tool is to display user image of people in your blog/website&#8217;s comment section. You can have a textbox where users can enter their twitter username and from this you can display their twitter avatar <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><h2>Code behind this simple tool</h2><p><img src="http://viralpatel.net/blogs/wp-content/uploads/twitter-logo.png" alt="twitter-logo" title="twitter-logo" width="201" height="63" class="alignright size-full wp-image-579" /><br /> We are using cURL to fetch the user details from Twitter. For this we are using the <a href="http://viralpatel.net/blogs/demo/Twitter.class.php.txt">Twitter PHP library</a> that we used in our previous <a href="http://viralpatel.net/blogs/2009/08/creating-simple-twitter-reader-client-5-minutes.html">Twitter Client tutorial</a>.</p><p>Following is the PHP source code of the Twitter User Image fetcher.</p><pre class="brush: php; title: ; notranslate">
&lt;?php
include(&quot;Twitter.class.php&quot;);
$twitter = new Twitter();

$username = $_REQUEST[&quot;user&quot;];

$json = $twitter-&gt;show('json', $username);
$user = json_decode($json);

$image_url = $user-&gt;profile_image_url;
header(&quot;Location: &quot;.$image_url);
?&gt;
</pre><p>First we use cURL to fetch the user details using twitter API. The response that we get is in JSON format. Hence we use PHP JSON method, json_decode() to convert the JSON into PHP object.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/08/creating-simple-twitter-reader-client-5-minutes.html" title="Creating a simple Twitter Reader(Client) in 5 minutes!!">Creating a simple Twitter Reader(Client) in 5 minutes!!</a></li><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/04/iterate-hashmap-using-jstl-foreach.html" title="How to iterate HashMap using JSTL forEach loop">How to iterate HashMap using JSTL forEach loop</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/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/12/dynamically-shortened-text-show-more-link-jquery.html" title="Dynamically shortened Text with &#8220;Show More&#8221; link using jQuery">Dynamically shortened Text with &#8220;Show More&#8221; link using 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></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/08/display-twitter-user-image-on-your-blogwebsite-in-2-minutes.html/feed</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Pillows for you: Try these Social Media Pillow</title><link>http://viralpatel.net/blogs/2009/08/pillows-try-social-media-pillow.html</link> <comments>http://viralpatel.net/blogs/2009/08/pillows-try-social-media-pillow.html#comments</comments> <pubDate>Tue, 11 Aug 2009 14:26:25 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Fun]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[digg]]></category> <category><![CDATA[facebook]]></category> <category><![CDATA[social media]]></category> <category><![CDATA[tech stories]]></category> <category><![CDATA[twitter]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1642</guid> <description><![CDATA[You will find those Social Media buttons on most of the blogs and websites you visit these days. Even we have one such button panel at the end of each post which lets user share the story with their favorite social website. But guess what, Chicago-based Twitter user @craftsquatch has created series of pillows hand [...]]]></description> <content:encoded><![CDATA[<p>You will find those Social Media buttons on most of the blogs and websites you visit these days. Even we have one such button panel at the end of each post which lets user share the story with their favorite social website.</p><p>But guess what, Chicago-based Twitter user <strong>@craftsquatch</strong> has created series of pillows hand decorated to represent your favorite social networking sites, might be what you need. , the pillows produced include Flickr, Reddit, Digg (Digg), the Twitter “t”, the Fail Whale, the Twitter bird, FriendFeed (FriendFeed), Tumblr (Tumblr), Facebook (Facebook), MySpace (MySpace) and more.</p><p>The pillows are available for $18 each in the <a rel="nofollow" target="_new" href="http://www.etsy.com/shop.php?user_id=6956228">Craftsquatch Etsy store</a>.</p><h2>Social Media Pillows: Photo Gallery</h2><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/socialpillows1.jpg" class="aligncenter" /></p><p><img src="http://img.viralpatel.net/2009/08/socialpillows2.gif" alt="socialpillows2" title="socialpillows2" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/socialpillows3.gif" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/socialpillows5.gif" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/failwhalepillow.jpg" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/diggpillow.jpg" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/tumblrpillow.jpg" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/flickrpillow.jpg" class="aligncenter" /></p><p><img alt="" src="http://ec.mashable.com/wp-content/uploads/2009/08/rsspillow.jpg" class="aligncenter" /></p><p>Photo courtesy: <a rel="nofollow" target="_new" href="http://mashable.com/2009/08/11/social-media-pillows/">Mashable</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/02/did-twitter-forget-to-update-copyright-year.html" title="Did Twitter Forget to Update its Copyright Year?">Did Twitter Forget to Update its Copyright Year?</a></li><li><a href="http://viralpatel.net/blogs/2009/11/google-wave-fail-whale.html" title="Google Wave has its own Fail Whale">Google Wave has its own Fail Whale</a></li><li><a href="http://viralpatel.net/blogs/2009/08/what-if-facebook-is-country.html" title="What if the Facebook is a Country?">What if the Facebook is a Country?</a></li><li><a href="http://viralpatel.net/blogs/2009/08/if-twitter-consisted-of-100-people.html" title="If Twitter Consisted of 100 People!">If Twitter Consisted of 100 People!</a></li><li><a href="http://viralpatel.net/blogs/2009/07/precrime-minority-report-real-facebook-england.html" title="Pre-crime &#038; Minority Report turns real through Facebook in England">Pre-crime &#038; Minority Report turns real through Facebook in England</a></li><li><a href="http://viralpatel.net/blogs/2009/06/facebook-vanity-urls-landrush-starts-june-13-midnight.html" title="Facebook Vanity URLs Landrush to starts on June 13 Midnight">Facebook Vanity URLs Landrush to starts on June 13 Midnight</a></li><li><a href="http://viralpatel.net/blogs/2009/04/breaking-news-twitter-hit-by-stalkdaily-virus.html" title="Breaking News: Twitter hit by StalkDaily Virus">Breaking News: Twitter hit by StalkDaily Virus</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/08/pillows-try-social-media-pillow.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Creating a simple Twitter Reader(Client) in 5 minutes!!</title><link>http://viralpatel.net/blogs/2009/08/creating-simple-twitter-reader-client-5-minutes.html</link> <comments>http://viralpatel.net/blogs/2009/08/creating-simple-twitter-reader-client-5-minutes.html#comments</comments> <pubDate>Mon, 10 Aug 2009 09:24:20 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[twitter]]></category> <category><![CDATA[twitter api]]></category> <category><![CDATA[twitter client]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1636</guid> <description><![CDATA[Twitter, The popular micro blogging and real time update site has changed the way we interact in internet world. Not only it has became a source of latest updates/news going in world, but also an addiction to lot of those who tweets regularly. Twitter has provided lots of API that can be used to Get [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/08/twitter-client-reader.png" alt="twitter-client-reader" title="twitter-client-reader" width="500" height="464" class="aligncenter size-full wp-image-1637" /><br /> Twitter, The popular micro blogging and real time update site has changed the way we interact in internet world. Not only it has became a source of latest updates/news going in world, but also an addiction to lot of those who tweets regularly.</p><p>Twitter has provided lots of API that can be used to Get the latest tweets / Add tweets / Search the tweets / Get the trends etc.. These APIs are REST APIs that can be called by using any scripting language and getting the result back. You can read full specifications of API at <a rel="nofollow" href="http://apiwiki.twitter.com/REST+API+Documentation">Twitter&#8217;s API</a> site.</p><p>Let us first see the small demo that I have created. This demo page will read latest public tweets every 10 second and update it on screen with some animation effect.</p><p><a target="_new" href="http://viralpatel.net/blogs/demo/twitter-reader.php"><strong>Click here to view the demo.</strong></a></p><p>We will use a PHP library to call the Twitter APIs and get the result. Following is the code of library. Just copy paste it in a file called <code>Twitter.class.php</code>.</p><pre class="brush: php; title: ; notranslate">
&lt;?php

	/* This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.

     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.

     * You should have received a copy of the GNU General Public License
     * along with this program.  If not, see &lt;http://www.gnu.org/licenses/&gt;.
     *
     * File:    Twitter.class.php
	 * Author:  Brandon Trebitowski
	 * Created: 02/26/2009
	 * Updated  06/24/09
	 * Version: 1.1
	 *
     */

	class Twitter {

		var $username='';
		var $password='';
		var $responseInfo=array(); 

		// Status Methods
		/*
		 * Returns the 20 most recent statuses from non-protected users
		 * who have set a custom user icon.  Does not require authentication.
		 * Note that the public timeline is cached for 60 seconds so requesting
		 * it more often than that is a waste of resources.
		 */
		function public_timeline($format) {
			$request = 'http://twitter.com/statuses/public_timeline.'.$format;
			return $this-&gt;process($request);
		 }

		 /* Returns the 20 most recent statuses posted by the authenticating
		  * user and that user's friends. This is the equivalent of /home on the Web.
		  */
		function friends_timeline($format='xml',$count=20) {
			$request = 'http://twitter.com/statuses/friends_timeline.'.$format;
			$postargs = &quot;count=$count&quot;;
			return $this-&gt;process($request,$postargs);
		}

		/* Returns the 20 most recent statuses posted from the authenticating user.
		 * It's also possible to request another user's timeline via the id parameter
		 * below. This is the equivalent of the Web /archive page for your own user,
		 * or the profile page for a third party.
		 */
		function user_timeline($format='xml',$id=null) {
			$request = 'http://twitter.com/statuses/user_timeline.'.$format;
			if($id) {
				$postargs = &quot;id=$id&quot;;
				return $this-&gt;process($request,$postargs);
			}
			return $this-&gt;process($request);
		}

		/* Updates the authenticating user's status.  Requires the status parameter
		 * specified below.  Request must be a POST.  A status update with text identical
		 * to the authenticating user's current status will be ignored.
		 */
		function update($format = 'xml',$status){
			$request = 'http://twitter.com/statuses/update.'.$format;
			$postargs = 'status='.urlencode($status);
			return $this-&gt;process($request,$postargs);
		} 

		/* Returns the 20 most recent @replies (status updates prefixed with @username)
		 * for the authenticating user.
		 */
		function replies($format='xml') {
			$request = 'http://twitter.com/statuses/replies.'.$format;
			return $this-&gt;process($request);
		}

		// User Methods
		/* Returns the authenticating user's friends, each with current status inline.
		 * They are ordered by the order in which they were added as friends. It's also
		 * possible to request another user's recent friends list via the id parameter below.
		 */
		function friends($format='xml',$id=null,$page=1) {
			$request = 'http://twitter.com/statuses/friends.'.$format;
			$postargs = &quot;page=$page&quot;;
			if($id) {
				$postargs .= &quot;&amp;amp;id=$id&quot;;
			}
			return $this-&gt;process($request,$postargs);
		}

		/* Returns the authenticating user's followers, each with current status inline.
		 * They are ordered by the order in which they joined Twitter (this is going to be changed).
		 */
		function followers($format='xml',$id=null,$page=1) {
			$request = 'http://twitter.com/statuses/followers.'.$format;
			$postargs = &quot;page=$page&quot;;
			if($id) {
				$postargs .= &quot;&amp;amp;id=$id&quot;;
			}
			return $this-&gt;process($request,$postargs);
		}

		/* Returns extended information of a given user, specified by ID or screen name
		 * as per the required id parameter below.  This information includes design settings,
		 * so third party developers can theme their widgets according to a given user's preferences.
		 * You must be properly authenticated to request the page of a protected user.
		 */
		function show($format='xml',$id) {
			$postargs = &quot;&quot;;

			$request = 'http://twitter.com/users/show/'.$id.&quot;.$format&quot;;

			return $this-&gt;process($request);
		}

		// Friendship Methods

		/* Befriends the user specified in the ID parameter as the authenticating user.
		 * Returns the befriended user in the requested format when successful.  Returns
		 * a string describing the failure condition when unsuccessful.
		 */
		function create($format='xml',$user_ID) {
			$request = &quot;http://twitter.com/friendships/create/$user_ID.$format&quot;;
			return $this-&gt;process($request);
		}

		/* Discontinues friendship with the user specified in the ID parameter as the
		 * authenticating user.  Returns the un-friended user in the requested format
		 * when successful.  Returns a string describing the failure condition when unsuccessful.
		 */
		function destroy($format='xml',$user_ID) {
			$request = &quot;http://twitter.com/friendships/destroy/$user_ID.$format&quot;;
			return $this-&gt;process($request);
		}

		/* Tests if a friendship exists between two users.
		 */
		function exists($format='xml',$user_ID_a,$user_ID_b) {
			$request = &quot;http://twitter.com/friendships/exists.$format?user_a=$user_ID_a&amp;amp;user_b=$user_ID_b&quot;;
			return $this-&gt;process($request);
		}

		/* Processes a Twitter Request using cURL */
		function process($url,$postargs=false){ 

			$curl_conn = curl_init();
			curl_setopt($curl_conn, CURLOPT_URL, $url); //URL to connect to
			//curl_setopt($curl_conn, CURLOPT_POST, 1); //Use GET method
			curl_setopt($curl_conn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); //Use basic authentication
			curl_setopt($curl_conn, CURLOPT_USERPWD, $this-&gt;username.&quot;:&quot;.$this-&gt;password); //Set u/p
			curl_setopt($curl_conn, CURLOPT_SSL_VERIFYPEER, false); //Do not check SSL certificate (but use SSL of course), live dangerously!
			curl_setopt($curl_conn, CURLOPT_RETURNTRANSFER, 1); //Return the result as string

			// Result from querying URL. Will parse as xml
			$output = curl_exec($curl_conn);

			// close cURL resource. It's like shutting down the water when you're brushing your teeth.

			$this-&gt;responseInfo=curl_getinfo($curl_conn);
			curl_close($curl_conn);

			if(intval($this-&gt;responseInfo['http_code'])==200){
				// Display the response from Twitter
				return $output;
			}else{
				// Something went wrong
				return &quot;Error: &quot; . $this-&gt;responseInfo['http_code'];
			}

		}
	}
?&gt;
</pre><p>Now create a file called twitter-reader.php in the same folder as of Twitter.class.php and copy following content in it.</p><pre class="brush: php; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Twitter Client example using PHP library - viralpatel.net&lt;/title&gt;
	&lt;style&gt;
		body {
			font-family: sans-serif;
			font-size: 13px;
		}
		#update {
			height: 65px;
			width: 500px;
			background-color: #EFEFEF;
			margin-bottom: 5px;
			padding: 5 5 5 5;
		}
		#update #left {
			float:left;
			display: inline;
			padding-right: 7px;
		}
		#update .user {
			font-weight: bold;
			color: #0383FF;
		}
	&lt;/style&gt;
	&lt;script src=&quot;jquery-1.3.1.min.js&quot; language=&quot;javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

	&lt;div id=&quot;updates&quot;&gt;

&lt;?php
include(&quot;Twitter.class.php&quot;);
$twitter = new Twitter();

$json = $twitter-&gt;public_timeline('json');
$updates = json_decode($json);

foreach ($updates  as $update) {
//   echo $update-&gt;text;
//   echo $update-&gt;user-&gt;name . &quot;&lt;br&gt;&quot;;
?&gt;

		&lt;div id=&quot;update&quot;&gt;
			&lt;div id=&quot;left&quot;&gt;&lt;img width=&quot;48px&quot; height=&quot;48px&quot; src=&quot;&lt;?=$update-&gt;user-&gt;profile_image_url?&gt;&quot;/&gt;&lt;/div&gt;
			&lt;div id=&quot;right&quot;&gt;
				&lt;div class=&quot;user&quot;&gt;&lt;?=$update-&gt;user-&gt;name?&gt;&lt;/div&gt;
				&lt;div class=&quot;detail&quot;&gt;
				&lt;?=$update-&gt;text?&gt;
				&lt;/div&gt;
			&lt;/div&gt;
		&lt;/div&gt;
&lt;?php
}
?&gt;
	&lt;/div&gt;

&lt;script&gt;
$(document).ready(function(){
getlatest();
});
function getlatest() {

$.ajax({
	type: &quot;GET&quot;,
	url: &quot;latest-tweet.php&quot;,
	cache: false,
	success: function(html){
			$(&quot;div#updates&quot;).prepend(html);
			$(&quot;#update&quot;).slideDown(&quot;400&quot;);
		}
});

 setTimeout(&quot;getlatest();&quot;, 10000);
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>That&#8217;s it. Your simple twitter reader (client) that reads public tweets is ready. I have used some jQuery code to pull latest tweets every 10 seconds and display them on screen. For that we are using a php file latest-tweet.php which calls our PHP library and gets the latest tweet. Following is the content of latest-tweet.php</p><pre class="brush: php; title: ; notranslate">
&lt;?php
include(&quot;Twitter.class.php&quot;);
$twitter = new Twitter();

$json = $twitter-&gt;public_timeline('json');
$updates = json_decode($json);
$update = $updates[0];
?&gt;

&lt;div id=&quot;update&quot; style=&quot;display:none&quot;&gt;
	&lt;div id=&quot;left&quot;&gt;&lt;img width=&quot;48px&quot; height=&quot;48px&quot; src=&quot;&lt;?=$update-&gt;user-&gt;profile_image_url?&gt;&quot;/&gt;&lt;/div&gt;
	&lt;div id=&quot;right&quot;&gt;
		&lt;div class=&quot;user&quot;&gt;&lt;?=$update-&gt;user-&gt;name?&gt;&lt;/div&gt;
		&lt;div class=&quot;detail&quot;&gt;
		&lt;?=$update-&gt;text?&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;
</pre><p>Thus, all we need is three php files Twitter.class.php, twitter-reader.php and latest-tweet.php and that&#8217;s it.</p><p>There are different API functions available in Tweeter.class.php that can be used to do lot of things around twitter. Functions are pretty much self explanatory. Give it a try and let me know.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/08/display-twitter-user-image-on-your-blogwebsite-in-2-minutes.html" title="Display Twitter User Image on your Blog/Website in 2 Minutes">Display Twitter User Image on your Blog/Website in 2 Minutes</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html" title="How to implement Master/Detail forms using Spring Roo">How to implement Master/Detail forms using Spring Roo</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/06/tutorial-spring-3-mvc-introduction-spring-mvc-framework.html" title="Spring 3 MVC – Introduction to Spring 3 MVC Framework">Spring 3 MVC – Introduction to Spring 3 MVC Framework</a></li><li><a href="http://viralpatel.net/blogs/2010/02/did-twitter-forget-to-update-copyright-year.html" title="Did Twitter Forget to Update its Copyright Year?">Did Twitter Forget to Update its Copyright Year?</a></li><li><a href="http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" title="Tutorial: Create Struts2 Hibernate Example in Eclipse">Tutorial: Create Struts2 Hibernate Example in Eclipse</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/08/creating-simple-twitter-reader-client-5-minutes.html/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Google Map Geocoding Tutorial with Example</title><link>http://viralpatel.net/blogs/2009/07/google-map-geocoding-tutorial-example.html</link> <comments>http://viralpatel.net/blogs/2009/07/google-map-geocoding-tutorial-example.html#comments</comments> <pubDate>Wed, 01 Jul 2009 08:11:40 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[google maps]]></category> <category><![CDATA[mashup]]></category> <category><![CDATA[reverse geocode]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1484</guid> <description><![CDATA[Google Map API has been a great way to show geographical information on web. A lot of mashup tools like this, have been created around Google Maps to show a wide variety of data. In my previous article about Introduction to Google Maps API, I had described basic APIs to integrate Google Map in your [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/06/google-map-reverse-geocoding.png" alt="google-map-reverse-geocoding" title="google-map-reverse-geocoding" width="208" height="174" class="alignleft size-full wp-image-1485" /><strong>Google Map API</strong> has been a great way to show geographical information on web. A lot of <a href="http://viralpatel.net/blogs/2009/02/google-maps-and-twitter-mashup-show-uk-snowfall-google-map-twitter-mashup.html"><strong>mashup tools like this</strong></a>, have been created around <strong>Google Maps</strong> to show a wide variety of data. In my previous article about <a href="http://viralpatel.net/blogs/2009/01/introduction-to-google-maps.html"><strong>Introduction to Google Maps API</strong></a>, I had described basic APIs to integrate Google Map in your webpage. In this small article we will discuss a great feature of Google Maps API that can be used to locate any City/Country/Place on Map. This is called <strong>Geocoding</strong>.</p><p>Google Maps API provides a wonderful API called Geocoding API that enables you to fetch any location and pin point it on Google Map. <code>GClientGeocoder</code> is the class that we use to get the geocoder that get us the location. We will use <strong>getLatLng()</strong> method to get latitude/longitude of any location.<br /> Check the following code.</p><pre class="brush: jscript; title: ; notranslate">
var place =  &quot;New York&quot;;
geocoder = new GClientGeocoder();
geocoder.getLatLng(place, function(point) {
	if (!point) {
		alert(place + &quot; not found&quot;);
	} else {
		var info = &quot;&lt;h3&gt;&quot;+place+&quot;&lt;/h3&gt;Latitude: &quot;+point.y+&quot;  Longitude:&quot;+point.x;
		var marker = new GMarker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(info);
	}
});
</pre><p>In above code snippet we passed string &#8220;New York&#8221; and a handler function to getLatLng() method of GClientGeocoder. GClientGeocoder class will call google server for the location and when it gets the result, it pass the result to the handler function that we specified. Thus handler function will get point (GPoint) object from which we can get the latitude and longitude of location. In above code we have created a marker and placed it on the map.</p><h2>Online Demo</h2><p><a href="http://viralpatel.net/blogs/demo/google-map-reverse-geocoding.html" target="_new"><strong>Google Map Reverse Geocode Example</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/2009/02/google-maps-and-twitter-mashup-show-uk-snowfall-google-map-twitter-mashup.html" title="Google Maps and Twitter mashup show UK snowfall !!">Google Maps and Twitter mashup show UK snowfall !!</a></li><li><a href="http://viralpatel.net/blogs/2009/01/introduction-to-google-maps.html" title="Introduction to Google Maps.">Introduction to Google Maps.</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/07/google-map-geocoding-tutorial-example.html/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>RESTful Web Service tutorial: An Introduction for beginners</title><link>http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html</link> <comments>http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html#comments</comments> <pubDate>Wed, 24 Jun 2009 09:07:19 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[rest]]></category> <category><![CDATA[rest php]]></category> <category><![CDATA[restful]]></category> <category><![CDATA[restful java]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[webservices]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1448</guid> <description><![CDATA[REST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. Representational State Transfer(REST), a software architecture style used in developing stateless web services. While this style may be used to describe any distributed framework that uses [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/06/restful-web-services-rest.gif" alt="restful-web-services-rest" title="restful-web-services-rest" width="334" height="239" class="alignleft size-full wp-image-1450" />REST is a term coined by <a href="http://en.wikipedia.org/wiki/Roy_Fielding">Roy Fielding</a> in his Ph.D. dissertation to describe an architecture style of networked systems. <strong>REST</strong> is an acronym standing for <strong>Representational State Transfer</strong>. Representational State Transfer(REST), a software architecture style used in developing <strong>stateless web services</strong>. While this style may be used to describe any distributed framework that uses a simple protocol for data transmission and no other additional data transfer rules, the most common use of REST is on on the Web with HTTP being the only protocol used here. In <strong>REST</strong> each service (called &#8220;resource&#8221; in REST) is viewed as resource identified by a URL, and the only operations allowed are the HTTP &#8211; <strong>GET (Read), PUT (Update), POST(Create) and DELETE (Delete)</strong>. You can find this style similar in SQL, thinking of a resource as equivalent to a Table. The main features and constraints of REST architectural style are:</p><ul><li><strong>Client-Server</strong>: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.</li><li><strong>Stateless</strong>: All REST resources are required to be stateless. The idea is that the application would be resilient enough to work between server restarts. However, it is not uncommon to see some RESTful web services save states between requests.</li><li><strong>Caching</strong>: Caching is allowed, however it is required that &#8220;response to a request be implicitly or explicitly labeled as cacheable or non-cacheable&#8221;</li><li>As there is no interface definition (like in SOAP), it becomes mandatory for a Client and Server to have a mutual understanding of the messages being transmitted between them.</li></ul><p>Given that every resource in a RESTful service is represented by a URL, it is easy to write a client for such a web service.</p><p>A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.</p><h2>REST in PHP</h2><p>An example would be <a rel="nofollow" href="http://developer.yahoo.com/maps/rest/V1/geocode.html">Yahoo!’s Geocoding API</a>, with the following URL:</p><pre class="brush: xml; title: ; notranslate">

http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&#038;street=701+First+Street&#038;city=Sunnyvale&#038;state=CA
</pre><p>You will get:</p><pre class="brush: xml; title: ; notranslate">
&lt;Result precision=&quot;address&quot;&gt;
   &lt;Latitude&gt;37.416384&lt;/Latitude&gt;
   &lt;Longitude&gt;-122.024853&lt;/Longitude&gt;
   &lt;Address&gt;701 FIRST AVE&lt;/Address&gt;
   &lt;City&gt;SUNNYVALE&lt;/City&gt;
   &lt;State&gt;CA&lt;/State&gt;
   &lt;Zip&gt;94089-1019&lt;/Zip&gt;
   &lt;Country&gt;US&lt;/Country&gt;
&lt;/Result&gt;
</pre><p>So Yahoo! exposes the Geocode URL and allows you to query this resource using URL parameters like appid and street. Dynamically building your URL to query a given resource is OK, generally that’s what people do, like the following:</p><pre class="brush: php; title: ; notranslate">
$base = 'http://xml.amazon.com/onca/xml3';
$query_string = &quot;&quot;;

$params = array( 'ManufacturerSearch' =&gt; &quot;O'Reilly&quot;,
    'mode'  =&gt; 'books',
    'sort'  =&gt; '+salesrank',
    'page'  =&gt; 1,
    'type'  =&gt; 'lite',
    'f'     =&gt; 'xml',
    't'     =&gt; 'trachtenberg-20' ,
    'dev-t' =&gt; 'XXXXXXXXXXXXXX' ,
);

foreach ($params as $key =&gt; $value) {
    $query_string .= &quot;$key=&quot; . urlencode($value) . &quot;&amp;&quot;;
}

$url = &quot;$base?$query_string&quot;;
$output = file_get_contents($url);
</pre><p>You may want to see the pear package <a rel="nofollow" href="http://pear.php.net/package/HTTP_Request/">HTTP Request</a> for making REST calls, which among many things supports GET/POST/HEAD/TRACE/PUT/DELETE, basic authentication, proxy, proxy authentication, SSL, file uploads and more. Using this package, I got started on a simple wrapper class called RESTclient, which gives intuitive support for making REST resource calls.</p><p>So if we are going to use RESTclient to call the Geocode API above, following will be the source code:</p><pre class="brush: php; title: ; notranslate">
&lt;?php

require_once &quot;RESTclient.php&quot;;

$rest = new RESTclient();

$inputs = array();
$inputs[&quot;appid&quot;] = &quot;YahooDemo&quot;;
$inputs[&quot;street&quot;] = &quot;701 First Street&quot;;
$inputs[&quot;city&quot;] = &quot;Sunnyvale&quot;;
$inputs[&quot;state&quot;] = &quot;CA&quot;;

$url = &quot;http://api.local.yahoo.com/MapsService/V1/geocode/&quot;
$rest-&gt;createRequest(&quot;$url&quot;,&quot;POST&quot;,$inputs);
$rest-&gt;sendRequest();
$output = $rest-&gt;getResponse();
echo $output;

?&gt;
</pre><h2>REST in Java</h2><p>You may want to call the REST web service from Java. Following is the code for a simple Web Service client for the flickr web services interface.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.rest;

import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class FlickrClient {
	public static void main(String[] args) {
		String flickrURL = &quot;http://api.flickr.com/services/rest/?method=flickr.test.echo&amp;name=value&amp;api_key=[yourflickrkey]&quot;;

		try {
			SocketAddress addr = new InetSocketAddress(&quot;[proxy]&quot;, 9090);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
			URL u = new URL(&quot;http://api.flickr.com/services/rest/?method=flickr.test.echo&amp;name=value&amp;api_key=[yourflickrkey]&quot;);
			HttpURLConnection uc = (HttpURLConnection) u.openConnection(proxy);
			uc.setRequestProperty(&quot;Accept&quot;, &quot;*/*&quot;);
			uc.setRequestProperty(&quot;Accept-Charset&quot;, &quot;ISO-8859-1,utf-8;q=0.7,*;q=0.7&quot;);
			uc.setRequestProperty(&quot;Accept-Language&quot;, &quot;en-us,en;q=0.5&quot;);
			uc.setRequestProperty(&quot;Keep-Alive&quot;, &quot;300&quot;);
			uc.setRequestProperty(&quot;ucection&quot;, &quot;keep-alive&quot;);
			String proxyUser = &quot;[netUserId]&quot;;
			String proxyPassword = &quot;[netPassword]&quot;;
			uc.setRequestProperty(&quot;Proxy-Authorization&quot;, &quot;NTLM &quot; + new sun.misc.BASE64Encoder().encode((proxyUser + &quot;:&quot; + proxyPassword).getBytes()));

			DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = docBuilder.parse(uc.getInputStream());

			System.out.println(doc.getDocumentElement().getTagName());

			System.out.println();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
</pre><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/10/inner-classes-in-java.html" title="Inner classes in Java, the mystery within.">Inner classes in Java, the mystery within.</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li><li><a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html" title="15 very useful PHP code snippets for PHP developers">15 very useful PHP code snippets for PHP developers</a></li><li><a href="http://viralpatel.net/blogs/2009/02/file-upload-in-php-file-upload-php-file-upload-tutorial-securing-things.html" title="Tutorial: File upload in PHP, Securing the things.">Tutorial: File upload in PHP, Securing the things.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/create-jar-file-in-java-eclipse.html" title="Create JAR file in Java &#038; Eclipse">Create JAR file in Java &#038; Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/12/implement-ldap-authentication-in-tomcat-jboss-server-for-java-app.html" title="Implement LDAP authentication in Tomcat &#038; JBoss server for Java app">Implement LDAP authentication in Tomcat &#038; JBoss server for Java app</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></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html/feed</wfw:commentRss> <slash:comments>0</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-09 02:34:12 -->
