<?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/tag/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>Guys, I am writing a book</title>
		<link>http://www.vijayjoshi.org/2010/11/22/guys-i-am-writing-a-book/</link>
		<comments>http://www.vijayjoshi.org/2010/11/22/guys-i-am-writing-a-book/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 11:25:08 +0000</pubDate>
		<dc:creator>Vijay Joshi</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Resources]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.vijayjoshi.org/?p=671</guid>
		<description><![CDATA[
			
				
			
		

Yes that&#8217;s right and it is called PHP jQuery Cookbook.  As the name suggests, it&#8217;s about creating rich internet applications using 2 of my favorite technologies &#8211; PHP and jQuery.
I love coding web apps and helping others find solutions. Perhaps that is the reason I agreed to write when the wonderful people at Packt Publishing contacted me. (Also, a book ...]]></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%2F11%2F22%2Fguys-i-am-writing-a-book%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.vijayjoshi.org%2F2010%2F11%2F22%2Fguys-i-am-writing-a-book%2F&amp;source=v08i&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-630" title="PHP jQuery Cookbook" src="http://www.vijayjoshi.org/wp-content/uploads/2749OS_MockupCover_Cookbook_0.jpg" alt="PHP jQuery Cookbook" width="320" height="395" /></p>
<p>Yes that&#8217;s right and it is called <strong><a title="PHP jQuery Cookbook" href="https://www.packtpub.com/php-jquery-cookbook-to-create-interactive-web-applications/book">PHP jQuery Cookbook</a></strong>.  As the name suggests, it&#8217;s about creating rich internet applications using 2 of my favorite technologies &#8211; PHP and jQuery.</p>
<p>I love coding web apps and helping others find solutions. Perhaps that is the reason I agreed to write when the wonderful people at <a title="Packt Publishing" href="http://www.packtpub.com/">Packt Publishing</a> contacted me. (Also, a book on resume isn&#8217;t that bad either <img src='http://www.vijayjoshi.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> )</p>
<p>Another reason is I love Open source. It is a lovely philosophy and I am a strong believer in it. Having learnt so much from the Open source community since I started coding, I have always wanted to return something back. Nothing could have been better then this. And did I mention, Packt pays <a title="Packt Open Source Royalties" href="http://authors.packtpub.com/content/open-source-royalties">direct royalty to a project</a> if they sell a book written on the same.</p>
<p><strong><span id="more-671"></span></strong></p>
<p>Long story short, the book is cookbook with around 65 recipes covering PHP, jQuery, MySql and some API&#8217;s (Flickr, Youtube).</p>
<p>Structure wise, it has 10 chapters in all.</p>
<ul>
<li>Handling Events</li>
<li>Combining PHP and jQuery</li>
<li>Working with XML documents</li>
<li>Working with JSON</li>
<li>Working with Forms</li>
<li>Adding Visual effects to forms</li>
<li>Creating cool Navigation Menus</li>
<li>Data binding with PHP and jQuery</li>
<li>Enhancing your site with PHP and jQuery</li>
<li>Appendix &#8211; FireBug</li>
</ul>
<p>The book is available now <span style="text-decoration: line-through;">will be available by 14th December</span> <del datetime="2010-12-01T06:28:41+00:00">Christmas this year or January next year</del>. You can have a look in detail about what it is all about on Packt Website. Order a copy in case you find it interesting <img src='http://www.vijayjoshi.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div class="shr-publisher-671"></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%2F11%2F22%2Fguys-i-am-writing-a-book%2F' data-shr_title='Guys%2C+I+am+writing+a+book'></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/11/22/guys-i-am-writing-a-book/feed/</wfw:commentRss>
		<slash:comments>6</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>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>
	</channel>
</rss>

