<?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>vijayjoshi.org &#187; Ajax</title>
	<atom:link href="http://www.vijayjoshi.org/category/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.vijayjoshi.org</link>
	<description>php &#124; javascript &#124; ajax &#124; and all things web</description>
	<lastBuildDate>Sun, 20 Nov 2011 15:24:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Using Twitter API and jQuery to display recent tweets</title>
		<link>http://www.vijayjoshi.org/2010/12/24/using-twitter-api-and-jquery-to-display-recent-tweets/</link>
		<comments>http://www.vijayjoshi.org/2010/12/24/using-twitter-api-and-jquery-to-display-recent-tweets/#comments</comments>
		<pubDate>Fri, 24 Dec 2010 06:52:13 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=886</guid>
		<description><![CDATA[
			
				
			
		
In this article I will show you how you can display your (or any other user&#8217;s) recent tweets with some jQuery magic. We will create a widget (sort of) that will fetch n number of latest tweets from public timeline of a user using Twitter API and then we will display them in a nice list.
End result will look like ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2010%2F12%2F24%2Fusing-twitter-api-and-jquery-to-display-recent-tweets%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2010%2F12%2F24%2Fusing-twitter-api-and-jquery-to-display-recent-tweets%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>In this article I will show you how you can display your (or any other user&#8217;s) recent tweets with some jQuery magic. We will create a widget (sort of) that will fetch n number of latest tweets from public timeline of a user using Twitter API and then we will display them in a nice list.</p>
<p>End result will look like the following.</p>
<p style="text-align: left;"><img class="aligncenter size-full wp-image-887" title="tweets" src="http://www.vijayjoshi.org/wp-content/uploads/tweets.png" alt="tweets" width="480" height="388" /></p>
<p style="text-align: left;">Have a look at a live example.</p>
<p style="text-align: center;"><a href="http://vijayjoshi.org/examples/twitter-latest-tweets.html"><img class="size-full wp-image-453 aligncenter" title="View Demo" src="http://www.vijayjoshi.org/wp-content/uploads/demo.png" alt="View Demo" width="180" height="45" /></a></p>
<p style="text-align: left;">Let us start creating it now. First write some HTML. Define some css styles in the head section which will control the display of list. In the body section, there is a select box with id <strong><em>layout</em></strong> which will be used to select either a wide or a narrow layout for displaying the tweets. Then create a <strong><em>div </em></strong>with id <strong>tweets</strong>. We will create a <strong><em>ul</em></strong> inside this div which will have tweets as list items.</p>
<p style="text-align: left;"><span id="more-886"></span></p>
<p style="text-align: left;">
<p style="text-align: left;">
<pre class="brush:xml">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
	&lt;head&gt;
		&lt;title&gt;Latest Tweets Widget - Vijay Joshi | http://vijayjoshi.org&lt;/title&gt;
		&lt;style type="text/css"&gt;
			body{ margin:0;font-family:verdana,arial;font-size:13px;width:100%;}
			p{margin:0;padding:5px;}
			span{font-size: 10px; font-weight: bold;}
			#container{margin:0 auto;padding:5px;width:600px;}
			#tweets{background-color:#ACAAFC;}
			#tweets ul, li{list-style:none;margin:0;padding:5px;}
			#tweets h2{margin: 0pt; padding:5px;}
			#tweets a { color: #FF0000;}
			.even{ border-bottom: 1px dotted #000;color:#343234;background-color:#FCFEFC;}
			.odd{border-bottom: 1px dotted #000;color:#343234;background-color:#DCDEFC;}
			.clear{	clear:both;	}
		&lt;/style&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;div id="container"&gt;
			&lt;strong&gt;Select layout&lt;/strong&gt;
			&lt;select id="layout"&gt;
				&lt;option value="600"&gt;Wide&lt;/option&gt;
				&lt;option value="300"&gt;Narrow&lt;/option&gt;
			&lt;/select&gt;
			&lt;div class="clear"&gt; &lt;/div&gt;
			&lt;div id="tweets"&gt;&lt;/div&gt;
		&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p style="text-align: left;">
<p style="text-align: left;"><strong>jQuery Code</strong></p>
<p style="text-align: left;">Just before the body tag closes, add path to jQuery library either from your local file system or the Google CDN.</p>
<p style="text-align: left;">
<pre class="brush:js">&lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt;</pre>
<p>With this we are ready to pull the tweets. Start by defining 2 variables <strong><em>userName</em></strong> and <strong><em>count</em></strong>. Inside document.ready add a change event handler to select box with id <strong>layout</strong>. It will change its width from 600px to 300px on selecting narrow and again back to 600px on selecting wide.</p>
<p>Now call a function <strong>getTweets </strong>and pass user name and number of tweets to it.</p>
<pre class="brush:js">var userName = 'v08i';
var count = 8;
$(document).ready(function()
{
	$('#layout').change(function()
	{
		$('#container').css({ 'width' : $(this).val()+ 'px'});
	});
	getTweets(userName, count);

});</pre>
<p>getTweets function will actually contact the Twitter API and will fetch tweets from there. We will request the response in JSON format from Twitter using jQuery&#8217;s <strong>getJSON </strong>method.</p>
<p>Before we proceed let us talk a bit technical. As you probably know, browsers do not allow cross-domain ajax requests due to security reasons. In this case the example we are creating is at domain <span style="text-decoration: underline;">vijayjoshi.org</span> while the twitter domain is <span style="text-decoration: underline;">api.twitter.com</span>. If both domains were same, a simple AJAX request would have sufficed. To overcome this problem JSONP aka &#8220;JSON with Padding&#8221; is used.</p>
<p>To use JSONP with jQuery, just change the <strong>dataType</strong> parameter from <strong>json</strong> to <strong>jsonp</strong>. Now you do not have to worry about cross domain restriction or anything else. Just define a callback function (showTweets in this example) and you will receive the JSON response there.</p>
<pre class="brush:js">function getTweets(userName, count)
{
	$.getJSON(
		'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + userName + '&amp;count='+ count +'&amp;callback=?',
		{},
		showTweets,
		'jsonp'
	);
}</pre>
<p>Now that we have the response, define <strong>showTweets</strong> function, iterate in the results and display them. Here is how.</p>
<pre class="brush:js">function showTweets(tweets)
{
	var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
	var str = '&lt;ul&gt;';
	str+= '&lt;h2&gt;Recent Tweets from ' + userName +'&lt;/h2&gt;';
	var i = 0;
	$.each(tweets, function(index,value)
	{
		if(i == count)	return;
		var dt = new Date(value.created_at);
		str+= '&lt;li&gt;&lt;p&gt;';
		str+= value.text;
		str+= '&lt;/p&gt;';
		str+='&lt;span&gt;';
		str+= dt.getDate() + '-' + months[dt.getMonth()] + '-' + dt.getFullYear();
		str+= ' at ' + dt.getHours() + ':' +dt.getMinutes();
		str+= ' From ' + value.source;
		str+= '&lt;/span&gt;&lt;/li&gt;';
		i++;
	});
	str+= '&lt;/ul&gt;';
	$('#tweets').html(str);
	$('#tweets &gt; ul &gt; li:odd').addClass('odd');
	$('#tweets &gt; ul &gt; li:even').addClass('even');
}</pre>
<p>I have used only some of the values from the JSON response. You can view the full response by typing the following into your browser.</p>
<pre class="brush:as3">http://api.twitter.com/1/statuses/user_timeline.json?screen_name=your_twitter_username&amp;count=10</pre>
<p>With this we are done. Have a look at the demo I have created.</p>
<p style="text-align: center;"><a href="http://vijayjoshi.org/examples/twitter-latest-tweets.html"><img class="size-full wp-image-453 aligncenter" title="View Demo" src="http://www.vijayjoshi.org/wp-content/uploads/demo.png" alt="View Demo" width="180" height="45" /></a></p>
<p>For full source code, just view page source. It&#8217;s all happening on your browser after all.</p>
<p>If you have any questions, let me know in comments.</p>
<div class="shr-publisher-886"></div><!-- Start Shareaholic LikeButtonSetBottom --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:right;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fwww.vijayjoshi.org%2F2010%2F12%2F24%2Fusing-twitter-api-and-jquery-to-display-recent-tweets%2F' data-shr_title='Using+Twitter+API+and+jQuery+to+display+recent+tweets'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://www.vijayjoshi.org/2010/12/24/using-twitter-api-and-jquery-to-display-recent-tweets/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Collection of 10 top 10 lists about web development</title>
		<link>http://www.vijayjoshi.org/2009/09/23/collection-of-10-top-10-lists-about-web-development/</link>
		<comments>http://www.vijayjoshi.org/2009/09/23/collection-of-10-top-10-lists-about-web-development/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 13:02:25 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Resources]]></category>
		<category><![CDATA[firefox]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=401</guid>
		<description><![CDATA[
			
				
			
		
I am a regular reader of web development articles and in this process bookmark a lot of them. Out of that collection I present to you a list of 10 articles which themselves are lists of 10(tips, functions etc). Not all of them are top 10   but equally good. All these articles are related to php, javascript, html, ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F09%2F23%2Fcollection-of-10-top-10-lists-about-web-development%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F09%2F23%2Fcollection-of-10-top-10-lists-about-web-development%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I am a regular reader of web development articles and in this process bookmark a lot of them. Out of that collection I present to you a list of 10 articles which themselves are lists of 10(tips, functions etc). Not all of them are top 10 <img src='http://www.vijayjoshi.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  but equally good. All these articles are related to php, javascript, html, mysql and web development in general.</p>
<h3><a title="10 code snippets for PHP developers" href="http://htmlblog.net/10-code-snippets-for-php-developers/" target="_self">1-  10 code snippets for PHP developers</a></h3>
<p>Simple and handy functions for common tasks like validating email address and XSL transformation.</p>
<p>&nbsp;</p>
<h3><a title="10 Advanced PHP Tips Revisited" href="http://www.smashingmagazine.com/2009/03/24/10-useful-php-tips-revisited/" target="_self">2- 10 Advanced PHP Tips Revisited</a></h3>
<p>Detailed and excellent tips from famous PHP gurus Chris Shiflett and Sean Coates.</p>
<p>&nbsp;</p>
<h3><a title="Top 10 PHP frameworks" href="http://www.phpframeworks.com/top-10-php-frameworks/" target="_self">3- Top 10 PHP frameworks</a></h3>
<p>PHP frameworks are quite popular among developers these days. This site is dedicated to php frameworks alone. In this article all frameworks have been compared for features. Very useful to help you in decision making if you are planning to use a framework for your next project.</p>
<p>&nbsp;</p>
<h3><a title="Top 10 custom JavaScript functions" href="http://www.dustindiaz.com/top-ten-javascript/" target="_self">4- Top 10 custom JavaScript functions of all time</a></h3>
<p>This is my favorite one. These 10 functions are a must in every web developer&#8217;s toolbox. Functions like getElementsByClass, toggle and cookie functions are included.</p>
<p>&nbsp;</p>
<h3><a title="JavaScript Tips and Best Practices" href="http://www.impressivewebs.com/10-javascript-quick-tips-and-best-practices/" target="_self">5- 10 JavaScript Quick Tips and Best Practices</a></h3>
<p>Another good article on javascript best practices.</p>
<p>&nbsp;</p>
<h3><a title="Top 10 Firefox Addons For Web Developers" href="http://www.hurricanesoftwares.com/top-10-firefox-addons-for-web-developers/" target="_self">6- Top 10 Firefox Addons For Web Developers</a></h3>
<p>Who hasn&#8217;t heard of Firebug or GreaseMonkey. This article lists similar addons for firefox that are a great help in web development.</p>
<p>&nbsp;</p>
<p><span id="more-401"></span></p>
<h3><a title="10 Ways to Improve Your Web Page Performance" href="http://sixrevisions.com/web-development/10-ways-to-improve-your-web-page-performance/" target="_blank">7- 10 Ways to Improve Your Web Page Performance</a></h3>
<p>From the article:</p>
<blockquote><p>
This article primarily focuses on front-end performance since it’s the easiest to work on and provides you the most bang for your buck.</p></blockquote>
<p>&nbsp;</p>
<h3><a title="Web Development Tricks" href="http://zygote.egg-co.com/10-dirty-little-web-development-tricks/" target="_self">8- 10 Dirty Little Web Development Tricks</a></h3>
<p>Simple tips to help you in web development.</p>
<p>&nbsp;</p>
<h3><a title="10 Rare HTML Tags You Really Should Know" href="http://net.tutsplus.com/articles/web-roundups/10-rare-html-tags-you-really-should-know/" target="_self">9- 10 Rare HTML Tags You Really Should Know</a></h3>
<p>List of 10 html tags that are not used frequently. Check them out. It is possible that you have not heard about some of them.</p>
<p>&nbsp;</p>
<h3><a title="10 Useful articles about Database design" href="http://woork.blogspot.com/2008/09/10-useful-articles-about-database.html" target="_self">10- 10 Useful articles about Database design</a></h3>
<p>From the article:</p>
<blockquote><p>
The list includes some tips to define relationships-entities model, common database design mistakes, database normalization, how to use PHP and SQL to create tables and relationships and a correct approach to define relationships between tables.</p></blockquote>
<div class="shr-publisher-401"></div><!-- Start Shareaholic LikeButtonSetBottom --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:right;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F09%2F23%2Fcollection-of-10-top-10-lists-about-web-development%2F' data-shr_title='Collection+of+10+top+10+lists+about+web+development'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://www.vijayjoshi.org/2009/09/23/collection-of-10-top-10-lists-about-web-development/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>5 JSON resources for web developers</title>
		<link>http://www.vijayjoshi.org/2009/09/02/5-json-resources-for-web-developers/</link>
		<comments>http://www.vijayjoshi.org/2009/09/02/5-json-resources-for-web-developers/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 13:06:05 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Resources]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=366</guid>
		<description><![CDATA[
			
				
			
		
JSON(Javascript Object Notation) is defined as a lightweight data interchange format and fat-free lightweight alternative to xml. Since json is the native data form of Javascript, it can be used on the browser more easily then XML.
If you are a web developer who works with javascript/ajax a lot and still wondering what this json thing is, here is the first ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F09%2F02%2F5-json-resources-for-web-developers%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F09%2F02%2F5-json-resources-for-web-developers%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>JSON(Javascript Object Notation) is defined as a lightweight data interchange format and fat-free lightweight alternative to xml. Since json is the native data form of Javascript, it can be used on the browser more easily then XML.</p>
<p>If you are a web developer who works with javascript/ajax a lot and still wondering what this json thing is, here is the first step to start with. Read <a title="Definition of JSON and its uses" href="http://www.vijayjoshi.org/2008/08/20/what-is-json-definition-and-uses-in-javascript/" target="_self">this post about json</a> and its uses.</p>
<p>Below is a list of 5 resources from where you can learn about json in detail.</p>
<h2><a title="json.org" href="http://json.org/" target="_self">1- json.org</a></h2>
<p>First place to go to find definitive information. Douglas crockford is the man who invented json. json.org is a one stop place for everything json.</p>
<h2><a title="Mastering JSON" href="http://www.hunlock.com/blogs/Mastering_json_%28_JavaScript_Object_Notation_%29" target="_self">2- Mastering JSON</a></h2>
<p>Detailed examples as well as retrieving and sending json data between browser and server. You cam also find tips on security and best practices.</p>
<h2><a title="JSON vs XML Debate" href="http://ajaxian.com/archives/json-vs-xml-the-debate" target="_self">3- JSON vs XML debate</a></h2>
<p>Arguments are going on between which is better to use as a data format. Go read and judge yourself.</p>
<h2>4- JSON with Ajax and PHP[video]</h2>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" height="340" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://www.youtube.com/v/BEZvnGSk6A4" /><embed type="application/x-shockwave-flash" width="560" height="340" src="http://www.youtube.com/v/BEZvnGSk6A4"></embed></object></p>
<h2>5- Slide on JSON</h2>
<p><object style="margin:0px" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javascriptobjectnotationjson-090330015205-phpapp01&amp;stripped_title=java-script-object-notation-json-1219489" /><param name="allowfullscreen" value="true" /><embed style="margin:0px" type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javascriptobjectnotationjson-090330015205-phpapp01&amp;stripped_title=java-script-object-notation-json-1219489" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<div class="shr-publisher-366"></div><!-- Start Shareaholic LikeButtonSetBottom --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:right;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F09%2F02%2F5-json-resources-for-web-developers%2F' data-shr_title='5+JSON+resources+for+web+developers'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://www.vijayjoshi.org/2009/09/02/5-json-resources-for-web-developers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a countdown timer in javascript</title>
		<link>http://www.vijayjoshi.org/2009/03/23/creating-a-countdown-timer-in-javascript/</link>
		<comments>http://www.vijayjoshi.org/2009/03/23/creating-a-countdown-timer-in-javascript/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 12:14:48 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Misc]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=308</guid>
		<description><![CDATA[
			
				
			
		
On one of the projects I am working upon currently, we needed a countdown timer in JavaScript. User had to fill in a form and we wanted to restrict that time to 5 minutes and simultaneously show him how many minutes/seconds are left now. After the set time limit is crossed user is informed that a timeout has occurred.
Here is ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F03%2F23%2Fcreating-a-countdown-timer-in-javascript%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F03%2F23%2Fcreating-a-countdown-timer-in-javascript%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>On one of the projects I am working upon currently, we needed a countdown timer in JavaScript. User had to fill in a form and we wanted to restrict that time to 5 minutes and simultaneously show him how many minutes/seconds are left now. After the set time limit is crossed user is informed that a timeout has occurred.</p>
<p>Here is the code for timer(call it timer.js):</p>
<pre class="brush:js">var timer = {
	minutes :0,
	seconds : 0,
	elm :null,
	samay : null,
	sep : ':',
	init : function(m,s,elm)
	{
		m = parseInt(m,10);
		s = parseInt(s,10);
		if(m &lt; 0 || s &lt;0 || isNaN(m) || isNaN(s)) { alert('Invalid Values'); return; }
		this.minutes = m;
		this.seconds = s;
		this.elm = document.getElementById(elm);
		timer.start();
	},
	start : function()
	{
		this.samay = setInterval((this.doCountDown),1000);
	},
	doCountDown : function()
	{
		if(timer.seconds == 0)
		{
			if(timer.minutes == 0)
			{
				clearInterval(timer.samay);
				timerComplete();
				return;
			}
			else
			{
				timer.seconds=60;
				timer.minutes--;
			}
		}
		timer.seconds--;
		timer.updateTimer(timer.minutes,timer.seconds);
	},
	updateTimer :  function(min,secs)
	{
		min = (min &lt; 10 ? '0'+min : min);
		secs = (secs &lt; 10 ? '0'+secs : secs);
		(this.elm).innerHTML = min+(this.sep)+secs;
	}
}
function timerComplete()
{
	alert('time out buddy!!!');
}</pre>
<p>To start the timer put these lines after you have included the timer.js</p>
<pre class="brush:js">window.onload = init;
function init()
{
    timer.init(0,55,'container');
}</pre>
<p>On the markup side create an element with id=container</p>
<p>init function accepts 3 parameters : minutes, seconds and the id of html element where the countdown will be displayed.<br />
You will also need a function which will run after the timer&#8217;s execution has completed. For this purpose there is the function timerComplete included in the timer.js file. Write any code here that you would like to execute after timer has terminated (like redirect the user).<br />
Also make sure that you have an html element with id set to container on your html page.<br />
Above timer will do a countdown for 55 seconds. After 55 seconds, function timerComplete will be executed.<br />
You can see a <a title="Timer Demo" href="http://www.vijayjoshi.org/examples/timer/timer.html" target="_self">demo here</a> and if you wish you can also view page source code for javascript code.</p>
<p>Download timer.js from this <a title="Timer.js" href="http://www.vijayjoshi.org/examples/timer/timer.js" target="_self">link</a></p>
<p><em>Give this  article a Thumbs-up on Stumbleupon if you liked it.</em></p>
<div class="shr-publisher-308"></div><!-- Start Shareaholic LikeButtonSetBottom --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:right;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fwww.vijayjoshi.org%2F2009%2F03%2F23%2Fcreating-a-countdown-timer-in-javascript%2F' data-shr_title='Creating+a+countdown+timer+in+javascript'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://www.vijayjoshi.org/2009/03/23/creating-a-countdown-timer-in-javascript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Automatic session timeout/logout using php and AJAX : Part II</title>
		<link>http://www.vijayjoshi.org/2008/12/12/automatic-session-timeout-logout-using-php-and-ajax-part-ii/</link>
		<comments>http://www.vijayjoshi.org/2008/12/12/automatic-session-timeout-logout-using-php-and-ajax-part-ii/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 05:31:16 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=200</guid>
		<description><![CDATA[
			
				
			
		
This article is final part of 2 part series in which you will learn how to logout a user after a specific amount of inactivity. In part 1, we used only php. In this part, we will extend this functionality and will use AJAX to automatically logout the user if the inactivity time is exceeded. Logout will be irrespective of ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2008%2F12%2F12%2Fautomatic-session-timeout-logout-using-php-and-ajax-part-ii%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2008%2F12%2F12%2Fautomatic-session-timeout-logout-using-php-and-ajax-part-ii%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em>This article is final part of 2 part series in which you will learn how to logout a user after a specific amount of inactivity. In part 1, we used only php. In this part, we will extend this functionality and will use <strong><a href="http://en.wikipedia.org/wiki/AJAX">AJAX </a></strong>to automatically logout the user if the inactivity time is exceeded. Logout will be irrespective of whether the user requests any page from server or not.</em></p>
<p><em>Understanding part 1 is necessary to complete part 2. You can <a href="http://www.vijayjoshi.org/2008/12/08/automatic-session-timeoutlogout-using-php-and-ajax/">read it here</a>.</em></p>
<p>Hope you enjoyed the last post. In last post you saw that we logged out the user if she requests a page from the server after certain inactivity period.</p>
<p>Would it not be better that if the application ended the session as soon as the timeout period expires without having to wait for the user to request the page again. Sure it would be and this is what you will learn in this article.</p>
<p><a href="http://www.vijayjoshi.org/examples/timeout_AJAX/index.html" target="_blank"><img class="size-full wp-image-453 aligncenter" title="View Demo" src="http://www.vijayjoshi.org/wp-content/uploads/demo.png" alt="View Demo" width="180" height="45" /></a> <a href="http://www.vijayjoshi.org/examples/timeout/download.php?file=second"><img class="size-full wp-image-451 aligncenter" title="download" src="http://www.vijayjoshi.org/wp-content/uploads/download.png" alt="download" width="180" height="45" /></a></p>
<p>So get ready now.</p>
<p>We will poll the server with AJAX to check if the timeout period has passed or not. The response of AJAX call will have a boolean value by which we will redirect the user. I will assume that you have working knowledge of AJAX and therefore will not explain the AJAX code in detail.</p>
<p>Here are the steps that we will follow:</p>
<p>1- Set a poller in javascript that will contact a php script in our example.</p>
<p>2- The php script will check the timeout status of user.</p>
<p>3- php script will return either true or false as AJAX response depending upon if the session is timed out or not.</p>
<p>4- Response true means timeout has expired, hence user will be redirected to home page whereas false means user is still logged in.</p>
<p>Let&#8217;s do it in code now.</p>
<p>First the javascript part.Create a file named <em><strong>ajax.js</strong></em> in the same directory where other files are placed with this code:</p>
<pre class="brush:js">window.onload = init;
var interval;
function init()
{
	interval = setInterval(trackLogin,1000);
}
function trackLogin()
{
	var xmlReq = false;
	try {
	xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	try {
	xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (e2) {
	xmlReq = false;
	}
	}
	if (!xmlReq &amp;&amp; typeof XMLHttpRequest != 'undefined') {
	xmlReq = new XMLHttpRequest();
	}

	xmlReq.open('get', 'check.php', true);
	xmlReq.setRequestHeader("Connection", "close");
	xmlReq.send(null);
	xmlReq.onreadystatechange = function(){
		if(xmlReq.readyState == 4 &amp;&amp; xmlReq.status==200) {
			if(xmlReq.responseText == "true")
			{
				clearInterval(interval);
				alert('You have been logged out.You will now be redirected to home page.');
				document.location.href = "index.html";
			}
		}
	}
}</pre>
<p>Line 1 says, execute the init function after the DOM is loaded. Then we declare a variable  interval.   <span id="more-200"></span> In init we use <em><strong>setInterval </strong></em>function. setInterval executes the function name passed as first parameter every number of milliseconds specified as second argument. In this case trackLogin will periodically execute after 1000 ms or 1 second. Keeping time limit this much low is not advisable as this will put too much load on servers. It must be somethingh like 5 to 10 minutes depending upon the requirement of the application.</p>
<p>Now we come to <em><strong>trackLogin</strong></em>. This is the function which will make an AJAX call to our php script.</p>
<p>Lines 9 till 21 create an instance of XMLHTTP object.</p>
<p>Line 23 opens a connection to the check.php file on the server using get method.</p>
<p>In line 26 we register the callback function i.e. when ajax call returns from the server.</p>
<p>Line 28 checks whether the response is true. true means user has been logged out on the server and thus will have to login again. Therefore, in line 30 we remove the polling by using clearinterval and redirect the user to homepage after informing that session has been terminated. No action is taken in case response is false.</p>
<p>This makes our javascript/AJAX part over. Moving to php now, there are some changes in php files also.</p>
<p>Open the file <em><strong>first.php</strong></em> and go to the function showLoggedIn. Paste this line between  declarations.</p>
<pre class="brush:php">echo'&lt;script type="text/javascript" src="ajax.js"&gt;&lt;/script&gt;';</pre>
<p>Do the same for <em><strong>second.php</strong></em>.</p>
<p><em><strong>checkIfTimedOut</strong></em> function has also been moved to a separate file called &#8216;timeCheck.php&#8217; since it will be used in 3 places now. So, delete the function definition for checkIfTimedOut from both these files and just before the line</p>
<pre class="brush:php">$hasSessionExpired = checkIfTimedOut();</pre>
<p>insert a new line</p>
<pre class="brush:php">require 'timeCheck.php';</pre>
<p>Now create another file called <em><strong>check.php</strong></em> (that we called through our polling function in javascript).</p>
<p>Here we will write a function <em><strong>timeCheck</strong></em> which will determine whether session ended or not. It will return true if timeOut has been exceeded,false otherwise.</p>
<pre class="brush:php">function timeCheck()
{
    if(!isset($_SESSION['isLoggedIn']) || !($_SESSION['isLoggedIn']))
    {
		//user is not logged in
	    session_unset();
	    return true;
	    exit;
    }
	else
	{
		// user is logged in
		require 'timeCheck.php';
		$hasSessionExpired = checkIfTimedOut();
		if($hasSessionExpired)
		{
			session_unset();
			return true;
		}
		else
		{
			return false;
		}
	}
}</pre>
<p>In line 3 we check if the user is logged in or not. If not then session_unset is called and we return true.</p>
<p>If the user is logged in control goes to line 13.</p>
<p>Here we include the file <em><strong>timeCheck.php</strong></em> which contains the definition for <em><strong>checkIfTimedOut</strong></em>. In the next line we call <em><strong>checkIfTimedOut()</strong></em>. As you know from previous post, this function calculates the difference between current time and last accessed time(which is stored in session variable <em><strong>loggedAt</strong></em>) and returns true if the difference is greater then the session variable <em><strong>timeOut</strong></em>.</p>
<p>If it returned true, we unset all session variables and return true.</p>
<p>Now add these lines to the file where we will call <em><strong>timeCheck</strong></em> function.</p>
<pre class="brush:php">session_start();
$stillLoggedIn = timeCheck();
echo $stillLoggedIn;</pre>
<p>Pretty simple, AJAX call will arrive at this page every second.And timeCheck() will be called each time.</p>
<p>Value of <em><strong>$stillLoggedIn</strong></em> will be returned as the response to the AJAX call.</p>
<p>That is all we have to do.</p>
<p>Now open the <em><strong>index.html</strong></em> in your browser and click on Login. This will log you in and take you to <em><strong>first.php</strong></em>. Stay inactive here for more than 5 seconds and you will see the alert that you have been logged out. Try the same for second.php.</p>
<p>If you keep on navigating between <em><strong>first.php</strong></em> and <em><strong>second.php</strong></em> in less then 5 seconds, your session will not end. Try changing the timeOut specified in first.php.</p>
<p>If you are on firefox and have firebug installed, you can see in the console that every second an AJAX call is being made to page.</p>
<p><a href="http://www.vijayjoshi.org/examples/timeout/download.php?file=second"><img class="size-full wp-image-451 aligncenter" title="download" src="http://www.vijayjoshi.org/wp-content/uploads/download.png" alt="download" width="180" height="45" /></a></p>
<p>That brings us to the end of this 2 part series. Hope you enjoyed it. If you have any questions or would like me to explain the code further, I will be most happy to do so. Please leave a comment or stumble the page if you liked this article.</p>
<div class="shr-publisher-200"></div><!-- Start Shareaholic LikeButtonSetBottom --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:right;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fwww.vijayjoshi.org%2F2008%2F12%2F12%2Fautomatic-session-timeout-logout-using-php-and-ajax-part-ii%2F' data-shr_title='Automatic+session+timeout%2Flogout+using+php+and+AJAX+%3A+Part+II'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://www.vijayjoshi.org/2008/12/12/automatic-session-timeout-logout-using-php-and-ajax-part-ii/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Automatic session timeout/logout using php and AJAX</title>
		<link>http://www.vijayjoshi.org/2008/12/08/automatic-session-timeoutlogout-using-php-and-ajax/</link>
		<comments>http://www.vijayjoshi.org/2008/12/08/automatic-session-timeoutlogout-using-php-and-ajax/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 14:14:23 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=171</guid>
		<description><![CDATA[
			
				
			
		
Part 2 is also available now. Read part 2
This article is Part 1 of 2 part series in which you will learn how to logout user after a specific amount of inactivity. In part 1, we will use only php. If the user remains inactive for a certain period of time and then requests a page from server, she will ...]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2008%2F12%2F08%2Fautomatic-session-timeoutlogout-using-php-and-ajax%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2008%2F12%2F08%2Fautomatic-session-timeoutlogout-using-php-and-ajax%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em>Part 2 is also available now. <a href="http://www.vijayjoshi.org/2008/12/12/automatic-session-timeout-logout-using-php-and-ajax-part-ii/">Read part 2</a></em></p>
<p><em>This article is Part 1 of 2 part series in which you will learn how to logout user after a specific amount of inactivity. In part 1, we will use only php. If the user remains inactive for a certain period of time and then requests a page from server, she will be logged out. In part 2, we will extend this functionality and will use AJAX to automatically logout the user if the inactivity time is exceeded.Logout will be irrespective of whether the user requests any page from server or not.</em></p>
<p>In this article we will write a little example in php that will logout a user if she is inactive [does not request any page from server] for a certain amount of time and redirect to a default page.</p>
<p><a href="http://www.vijayjoshi.org/examples/timeout_AJAX/index.html" target="_blank"><img class="size-full wp-image-453 aligncenter" title="View Demo" src="http://www.vijayjoshi.org/wp-content/uploads/demo.png" alt="View Demo" width="180" height="45" /></a> <a href="http://www.vijayjoshi.org/examples/timeout/download.php?file=second"><img class="size-full wp-image-451 aligncenter" title="download" src="http://www.vijayjoshi.org/wp-content/uploads/download.png" alt="download" width="180" height="45" /></a></p>
<p>In the example click Login in index.html to login. This will take you to first.php. Now navigate to second.php using the link.Sit back for 7-8 seconds and then either refresh the page or click the link for first page. If you take any action after 5 seconds you will be logged out, otherwise the requested page will be served.</p>
<p>Explanation follows.</p>
<p>index.html is the default page where the user lands. User is not logged in at the moment. Clicking the Login button takes the user to first.php where user authentication is done. In a real world situation, this link will be replaced with the standard username/password fields.The code for first.php looks like this:</p>
<pre class="brush:php">session_start();
if(!isset($_SESSION['isLoggedIn']) || !($_SESSION['isLoggedIn']))
{
	//code for authentication comes here
	//ASSUME USER IS VALID
	$_SESSION['isLoggedIn'] = true;
	/////////////////////////////////////////
	$_SESSION['timeOut'] = 5;
	$logged = time();
	$_SESSION['loggedAt']= $logged;
	showLoggedIn();
}
else
{
	$hasSessionExpired = checkIfTimedOut();
	if($hasSessionExpired)
	{
		session_unset();
		header("Location:index.html");
		exit;
	}
	else
	{
		$_SESSION['loggedAt']= time();// update last accessed time
		showLoggedIn();
	}

}</pre>
<p>In starting lines of first.php we check whether a session variable isLoggedIn is set to true or not. If it is not set, user authentication will be done. For this example we will just set the value of isLoggedIn to true, which means user is authenticated now. Of course, in a real application you will write proper code to check the user authenticity.</p>
<p><span id="more-171"></span></p>
<p>Now, when the user is logged in we specify the timeOut period crossing which the user will be logged out.</p>
<p>In the next line we get current time and store it in another session variable loggedAt.This is the time user has requested the page from server.</p>
<p>We have in total 3 session variables now.</p>
<p>isLoggedIn &#8211; tells whether user is logged in or not.</p>
<p>timeOut &#8211; Inactivity period in seconds after which user will be logged out and</p>
<p>loggedAt &#8211; last time when the user accessed a page.</p>
<p>After this showLoggedIn function is called which displays some html and a link to another page.</p>
<p>Code for showLoggedIn:</p>
<pre class="brush:php">function showLoggedIn()
{
	echo'&lt;html&gt;';
	echo'&lt;head&gt;';
	echo'&lt;/head&gt;';
	echo'&lt;body&gt;';
		echo'&lt;p&gt;';
			echo'Page 1. User is logged in currently.Timeout has been set to 5 seconds. If you stay inactive for more then 5 seconds, and then click the link below or refresh the page you will be logged out and redirected to home page.';
		echo'&lt;/p&gt;';
		echo'&lt;br/&gt;';
		echo'&lt;p&gt;&lt;a href="second.php"&gt;Go to second page&lt;/a&gt;&lt;/p&gt;';
		echo'&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;&lt;a href=""&gt;Back to article&lt;/a&gt;&lt;/p&gt;';
	echo'&lt;/body&gt;';
	echo'&lt;/html&gt;';
}</pre>
<p>Now what happens when the user refreshes the page after more then 5 seconds.</p>
<p>In line 3 session variable isLoggedIn is checked. Since it has been set to true already, control will go to the else part of if-else block i.e. line 16. In else a function checkIfTimedOut is called which determines whether the user has refreshed the page after more then timeOut period or not. if the value of variable $hasSessionExpired is true, we destroy all session variables and redirect user to index.html using header function.</p>
<p>Value false for $hasSessionExpired means the page has been refreshed in less then timeOut period. So we update the session variable loggedAt with current time and display the page again.<br />
Here is the code for function checkIfTimedOut:</p>
<pre class="brush:php">function checkIfTimedOut()
{
	$current = time();// take the current time
	$diff = $current - $_SESSION['loggedAt'];
	if($diff &gt; $_SESSION['timeOut'])
	{
		return true;
	}
	else
	{
		return false;
		$_SESSION['loggedAt']= time();// update last accessed time
	}
}</pre>
<p>In line we get the current time. Then we calculate the difference between current time and the time user logged in.</p>
<p>If the difference between these two is more then timeout period specified, we return true.<br />
Similar is the case when user clicks the link on page1. User will be taken to page2.php. First of all we check if the user is logged on using isLoggedIn. If not logged on, simply redirect user to index.html.</p>
<p>If already logged on then a call to checkIfTimedOut function checks whether timout has occurred. If it is a timeout then redirect user to home page else display page 2.<br />
Set the timeout to different values and then check.<br />
First part of article finishes here. Second part <span style="text-decoration: line-through;">will follow soon</span> is now available at <a href="http://www.vijayjoshi.org/2008/12/12/automatic-session-timeout-logout-using-php-and-ajax-part-ii/">this link</a>.</p>
<div class="shr-publisher-171"></div><!-- Start Shareaholic LikeButtonSetBottom --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:right;height:30px;'><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fwww.vijayjoshi.org%2F2008%2F12%2F08%2Fautomatic-session-timeoutlogout-using-php-and-ajax%2F' data-shr_title='Automatic+session+timeout%2Flogout+using+php+and+AJAX'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://www.vijayjoshi.org/2008/12/08/automatic-session-timeoutlogout-using-php-and-ajax/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

