<?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>Mission Data Blog &#187; javascript</title>
	<atom:link href="http://www.missiondata.com/blog/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.missiondata.com/blog</link>
	<description>Louisville-based Web Development &#38; Software Engineering</description>
	<lastBuildDate>Tue, 24 Jan 2012 14:58:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Handling Session Timeouts (and other errors) using Ajax</title>
		<link>http://www.missiondata.com/blog/web-development/83/handling-session-timeouts-and-other-errors-using-ajax/</link>
		<comments>http://www.missiondata.com/blog/web-development/83/handling-session-timeouts-and-other-errors-using-ajax/#comments</comments>
		<pubDate>Fri, 11 Jan 2008 20:18:11 +0000</pubDate>
		<dc:creator>steveny</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[session timeouts]]></category>

		<guid isPermaLink="false">http://www.missiondata.com/blog/uncategorized/83/handling-session-timeouts-and-other-errors-using-ajax/</guid>
		<description><![CDATA[Ajax can bring a much more responsive and intuitive feel to web applications. However, many times developers overlook error cases when using Ajax. What if the request fails? In one particular case a user&#8217;s session may have timed out before they made an Ajax call. This post describes one such way of handling this in [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Ajax_(programming)">Ajax</a> can bring a much more responsive and intuitive feel to web applications.  However, many times developers overlook error cases when using Ajax.  What if the request fails?  In one particular case a user&#8217;s session may have timed out before they made an Ajax call.  This post describes one such way of handling this in a somewhat friendly way.<br />
<span id="more-83"></span></p>
<h3>Handling session timeouts on non-Ajax requests</h3>
<p>The first step to handing session timeouts with AJAX is to handle them for non-Ajax requests first.  One way of doing this is trapping the URL the user is attempting to access  (but not authenticated to), redirecting them to a login page, and upon success, redirecting them back to their original request.</p>
<p>If they aren&#8217;t authenticated, send them to the login page:</p>
<pre><code>if(!loggedIn())
{
  response.sendRedirect("/login.jsp?uri=" + URLEncoder.encode(fullURI, "UTF8"));
}</code></pre>
<p>Hide the original request in the page:</p>
<pre><code></code>
<form action="/account/login" method="POST">
<input name="uri" type="hidden" value="&lt;%=request.getParameter(" />"&gt;
  <label for="user_login">ID:</label>
<input id="user_login" name="user_login" type="text" />
  <label for="user_password">Password:</label>
<input id="user_password" name="user_password" type="password" />
<input name="login" type="submit" />
</form>
</pre>
<p>&#8230;and after a successful signup, send them back to where they wanted to go:</p>
<pre><code>if(authenticated())
{
  response.sendRedirect(request.getParameter("uri"));
}</code></pre>
<h3>Handling Session Timeouts for Ajax Requests</h3>
<p>The first thing we need to know is if it is an ajax request or not.  Since I am going to use <a href="http://www.prototypejs.org/">prototype</a> for all my ajax calls it is as straight forward as looking for the special header prototype sends on each request:</p>
<pre><code>private boolean isXMLHttpRequest(HttpServletRequest request)
{
  return request.getHeader("x-requested-with") != null &amp;amp;&amp;amp; request.getHeader("x-requested-with").equals("XMLHttpRequest");
}</code></pre>
<p>Once we know the request type, we will send a non-200 <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP status code</a> if their is an authentication error.  From the standards, the most appropriate status code is a 401 (Unauthorized).  This code, however, comes with some baggage.  On a non-ajax HTTP request all browsers will respond by displaying an authentication dialog.  Most browsers don&#8217;t do this on ajax calls.  Most.  Safari decided that it should pop up the authentication dialog on ajax requests.  Without going too deeply into how this is probably correct and we should be using HTTP to its full advantage and using HTTP authentication instead of a custom authentication scheme, I don&#8217;t want this behavior.  I landed on using the much less appropriate 403 (Forbidden).</p>
<p>So, if the user isn&#8217;t authenticated  (such as with an expired session), send the 403 response back to the browser:</p>
<pre><code>if(isXMLHttpRequest(request))
{
  response.sendError(403);
}</code></pre>
<p>Now we handle the 403 on the browser side of things:</p>
<pre><code>new Ajax.Request('/search',
     {asynchronous:true,
       evalScripts:true,
       onException: function(req,exception) {
         alert('An exception "' + exception + '" was thrown accessing "' + request.url + '"' )
         return true
       },
       on403: function(t) {
         alert('Your session appears to have expired.  You will asked to log in again and returned here.')
         window.location.reload()
         return true
       },
       onFailure: function(request) {
         alert('An unhandled error occured ' + t.status + ': ' + t.statusText);
         return true
       },
       onLoading:function(request){Element.show('loading')},
       onComplete:function(request){Element.hide('loading')},
       onSuccess: function(t) {
         //do something with the results
       },
       parameters:Form.serialize(this)
     })</code></pre>
<p>The interesting bit of this call is the on403 method.  Prototype will call onXXX() where XXX is a non-200 HTTP response code.  When a 403 is returned, I simply reload the current page.  Since we handled the scenario of authenticating and returning to the requested page for the non-Ajax call, this &#8216;just works&#8217;.  You may wish to do something else here, including some nifty ajax widget that authenticates in-line and makes the call again.</p>
<p>Now that we have an Ajax request that suits our needs, we will want to use it throughout our project.  Instead of repeating the same code over and over again, let&#8217;s <a href="http://c2.com/cgi/wiki?DontRepeatYourself">DRY</a> it up.</p>
<h3>Creating a Wrapper Class</h3>
<p>Since I am going to use this scheme for <a href="http://www.prototypejs.org/api/ajax/request">Ajax.Request</a> and <a href="http://www.prototypejs.org/api/ajax/updater">Ajax.Updater</a> I created two wrapper classes that use a common function for setting the options.  This scheme allows you to override any of the default options I use in the wrapper:</p>
<pre><code>Ajax.MyRequest = Class.create(Ajax.Request, {
  initialize: function($super, url, options) {
    $super(url,_options(options));
  }
})

Ajax.MyUpdater = Class.create(Ajax.Updater, {
  initialize: function($super, container, url, options) {
    $super({success:container},url,_options(options));
  }
})

function _options(options) {
  return Object.extend({
     asynchronous:true,
     evalScripts:true,
     onException: function(request,exception) {
       Element.hide('loading')
       alert('An exception "' + exception + '" was thrown accessing "' + request.url + '"' )
       return true
     },
     on403: function(t) {
       Element.hide('loading')
       alert('Your session appears to have expired.  You will asked to log in again and returned here.')
       window.location.reload()
       return true
     },
     onFailure: function(t) {
       Element.hide('loading')
       alert('An unhandled error occured ' + t.status + ': ' + t.statusText);
     },
     onLoading:function(request){Element.show('loading')},
     onComplete:function(request){window.setTimeout('Element.hide("loading");', 100);}
  }, options || {});
}</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.missiondata.com/blog/web-development/83/handling-session-timeouts-and-other-errors-using-ajax/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>AJAX file upload progress for Java using commons fileupload and prototype</title>
		<link>http://www.missiondata.com/blog/web-development/28/file-upload-progress-with-ajax-and-java-and-prototype/</link>
		<comments>http://www.missiondata.com/blog/web-development/28/file-upload-progress-with-ajax-and-java-and-prototype/#comments</comments>
		<pubDate>Sun, 02 Apr 2006 21:15:15 +0000</pubDate>
		<dc:creator>carsonm</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blogs.missiondata.com/?p=28</guid>
		<description><![CDATA[This has been done before with PHP (AJAX upload progress meter for PHP) etc but I needed something a little different because I wanted to upload a file and then have it loaded into a database. I looked around and found that someone had already made something that used the commons file upload package to [...]]]></description>
			<content:encoded><![CDATA[<p>This has been done before with PHP (<a href="http://bluga.net/projects/uploadProgressMeter/">AJAX upload progress meter for PHP</a>) etc but I needed something a little different because I wanted to upload a file and then have it loaded into a database. I looked around and found that someone had already made something that used the commons file upload package to do the upload part (<a href="http://www.telio.be/blog/2006/01/06/ajax-upload-progress-monitor-for-commons-fileupload-example/">AJAX Upload progress monitor for Commons-FileUpload Example</a>). It wasn&#8217;t exactly what I was looking for but it a good start.</p>
<p>To understand the way this works I think it is easiest to break it down into parts:</p>
<ol>
<li>A file upload extention that counts bytes as they are uploaded</li>
<li>An interface that monitors the progress of something running on the server</li>
<li>AJAX to pull the monitoring into the current screen</li>
</ol>
<p><span id="more-28"></span></p>
<h3>Counting bytes when files are uploaded</h3>
<p>This was taken from the <a href="http://www.telio.be/blog/2006/01/06/ajax-upload-progress-monitor-for-commons-fileupload-example/">example listed above</a>. It extends and wraps parts of the commons File Upload classes so that you can count the bytes as they are uploaded to the server. You can download the <a href="http://blogs.missiondata.com/wp-content/uploads/2006/03/fileupload-ext.zip">source with build file</a> or the <a href="http://blogs.missiondata.com/wp-content/uploads/2006/03/fileupload-ext1.zip">binary</a>. You will also need the <a href="http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi">commons file upload</a>, <a href="http://jakarta.apache.org/site/downloads/downloads_commons-io.cgi">commons io</a> and <a href="http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi">commons logging</a>. If you download the source put the commons jars in the lib directory before building.</p>
<p>The code is fairly simple to follow. MonitoredDiskFileItemFactory replaces DiskFileItemFactory and the construction of a MonitoredDiskFileItemFactory takes a OutputStreamListener that will be passed on down the chain. The new factory creates MonitoredDiskFileItems instead of DiskFileItems for each file uploaded. When the file needs to be written to disk a MonitoredOutputStream is given back instead of a normal OutputStream. The MonitoredOutputStream calls the OutputStreamListener methods as the bytes are written and with that you now have a way to monitor the byte count as the file is created on the server.</p>
<p>Now to test this all out we can just have an OutputStreamListener that writes its progress out to a logfile or something.</p>
<pre>
<code>public class FileUploadListener implements OutputStreamListener
{
  private long totalFileSize;
  private long currentFileRead;

  public FileUploadListener(long totalFileSize)
  {
    this.totalFileSize = totalFileSize;
    this.currentFileRead = 0;
  }

  public void start()
  {
    log.debug("Upload started. Total file size: " + totalFileSize);
  }

  public void bytesRead(int byteCount)
  {
    log.debug("Read bytes. Currently " + byteCount + " out of " + totalFileSize + " bytes.");
    currentFileRead+=byteCount;
  }

  public void error(String error)
  {
    log.debug("Hit an error: " + error);
  }

  public void done()
  {
    log.debug("Upload done.");
  }

  public long getTotalRead()
  {
    return currentFileRead;
  }

  public long getTotalSize()
  {
    return totalFileSize;
  }
}</code>
</pre>
<p>Now we try it out. You can put this in a servlet or jsp so I&#8217;m only going to list the parts that matter.</p>
<pre>
<code>  FileUploadListener listener = new FileUploadListener(request.getContentLength());
  session.setAttribute("LISTENER", listener);
  FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
  ServletFileUpload upload = new ServletFileUpload(factory);
  List items = upload.parseRequest(request);
  for (Iterator i = items.iterator(); i.hasNext();)
  {
    FileItem fileItem = (FileItem) i.next();
    if (!fileItem.isFormField())
    {
       // code here to process the file
     }
   }</code>
</pre>
<p>I&#8217;m going to assume you can find the correct way to do the actual form upload part.</p>
<p>Note: One issue that you will face at some point is where the upload post goes to becuase when you get to the AJAXy part of things you want the post to stay on the same page. You can use a hidden iframe and the form&#8217;s &#8220;target&#8221; parameter to do this (I have an example later). This is one thing the Java examples I found didn&#8217;t have but the PHP examples did and I&#8217;m not sure exactly how the Java examples work without it.</p>
<h3>Monitoring progress on the server</h3>
<p>The next step is to monitor the progress of the upload on the server. What you are monitoring on the server doesn&#8217;t even need to be the upload. For the work I was doing the upload goes fairly quickly but what happens to the file after the upload takes a little longer. I wanted to monitor both and that is one reason I think it helps to break this up into parts because you aren&#8217;t limited to just monitoring file uploads.</p>
<p>The main thing to keep in mind here is that the application server is multithreaded and you can make more than one request to the server at the same time. You probably know that you can open a tab in firefox or another window in ie and use the same session from the current webapp you are using. Knowing that you can create a page that monitors the status of things as they are running on the server. </p>
<p>From the example above you could toss the listener into the users session. Then insead of logging you just add a couple variables to keep track of the number of bytes that have been uploaded. Then create a simple jsp that pulls the Listener out of the session and dumps its data to a page. Open two windows, one to the upload page and another one to the status page. Start the upload and then start refreshing the status. You should see that the values change as the file is uploaded.</p>
<pre>
<code>&lt;%@page%&gt;
&lt;%
  FileUploadListener listener = (FileUploadListener)session.getAttribute("LISTENER");
%&gt;
Total size: &lt;%=listener.getTotalSize()%&gt;&lt;br/&gt;
Read count: &lt;%=listener.getTotalRead()%&gt;&lt;br/&gt;</code>
</pre>
<p>Of course you will probably want more than just the total size and bytes read as well as more formating like a little progress bar or something but I&#8217;ll leave that up to you. </p>
<h3>AJAX integration with prototype</h3>
<p>You have the major parts to the upload progress done and now all you need is the AJAX part. To do this I chose to use <a href="http://prototype.conio.net/">prototype</a> because it cuts right to what you want to do. One call is all you need to use: Ajax.PeriodicalUpdater.</p>
<p>The Ajax.PeriodicalUpdater call will update a container (in my case a div) on a set interval. Here is an example of how to have it update a div with an id of &#8220;status&#8221; every second.</p>
<pre>
<code>    new Ajax.PeriodicalUpdater(
                                'status',
                                'status.jsp',
                                {asynchronous:true, frequency:1, method:'get'});</code>
</pre>
<p>The first argument is the id of the div, the second is the jsp that contains the data to stick into the div every second and the 3rd arguement is a set of options. There are more options availabe if you need them.</p>
<p>You would want to kick the update off whenever the form is posted. When the post is complete the iframe used as a place to post to will load with the results of the servlet or jsp that you posted to. If you return some javascript as a result for the iframe you will be able to create a final &#8220;finished&#8221; message on the page to let the user know the upload has completed and stop the processing of the AJAX updater.</p>
<p>So there you have it. The basics of setting up an upload progress bar using java and AJAX. I have left out a good bit but you should have enough to at least get you started.</p>
<p>By request I have created a simple example that pulls everything together. The source contains everything you need to create a war file including all source and an ant build file.</p>
<p><a href="/blog/examples/testupload.zip">Example Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.missiondata.com/blog/web-development/28/file-upload-progress-with-ajax-and-java-and-prototype/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
		<item>
		<title>Smooth scrolling image list</title>
		<link>http://www.missiondata.com/blog/web-development/13/smooth-scrolling-image-list/</link>
		<comments>http://www.missiondata.com/blog/web-development/13/smooth-scrolling-image-list/#comments</comments>
		<pubDate>Thu, 16 Feb 2006 02:26:03 +0000</pubDate>
		<dc:creator>carsonm</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blogs.missiondata.com/?p=13</guid>
		<description><![CDATA[I had someone ask me about fitting more images in a small area and the way flickr does their image scrolling came to mind. I wanted to see how hard it was to do and as it turns out it isn&#8217;t hard to do at all thanks to script.aculo.us. I&#8217;m making this as simple as [...]]]></description>
			<content:encoded><![CDATA[<p>I had someone ask me about fitting more images in a small area and the way flickr does their image scrolling came to mind. I wanted to see how hard it was to do and as it turns out it isn&#8217;t hard to do at all thanks to <a href="http://script.aculo.us/">script.aculo.us</a>.</p>
<p>I&#8217;m making this as simple as I can to illustrate just how nice the new tools like script.aculo.us are.</p>
<p><strong>Step 1.</strong> You need a box and some images. You will also need to know the size of the images or at least the size of the largest one. In an attempt to keep this simple I&#8217;m going to assume all the images are the same size.</p>
<pre>
<code>&lt;div id="imageBox"&gt;
  &lt;div id="imageBoxInside"&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/turtle_sm_1.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/elephants_sm_1.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/turtle_sm_2.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/elephants_sm_2.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/turtle_sm_3.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/elephants_sm_3.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/turtle_sm_4.jpg" /&gt;
    &lt;img src="http://blogs.missiondata.com/wp-admin/images/elephants_sm_4.jpg" /&gt;
    &lt;br/&gt;
  &lt;/div&gt;
&lt;/div&gt;</code>
</pre>
<p>Notice from this code that we have an outer box and an inner box. We will next want to make the outer box smaller than the inner box so that only a few of the images can be seen at one time.</p>
<p><strong>Step 2.</strong> To hide the extra images we give the outer box a set width, in this case I want to show only 2 images at a time and each image is 180px wide so I make the outer box 360px wide. Notice that the overflow is hidden. The hidden overflow is what keeps the images that are in the inner box but not within the outer box&#8217;s width hidden.</p>
<p>I&#8217;m using floats to lay the images out one next to the other. Because of this we need to give the inside box a large width so that it will not wrap the floated images.</p>
<pre>
<code>&lt;style type="text/css"&gt;
#imageBox { margin: auto; width: 360px; border: 1px #000 solid; overflow: hidden; }
#imageBoxInside { width: 10000px; }  #imageBox img { float: left; padding: 0px; margin: 0px; }
#imageBox br { clear: both; }
&lt;/style&gt;</code>
</pre>
<p><strong>Step 3.</strong> Now for the magic. You need the latest version of script.aculo.us because I use the Effects.Move function and they have changed Effects.MoveBy to Effects.Move only recently.</p>
<p>We now create two functions to move the images ether one step to the right or one step to the left. Each step is the size of a single image so the when one is hit it moves one image out of thew view and another image into view. As you can see from the following code this is extremely easy using the script.aculo.us library.</p>
<pre>
<code>&lt;script&gt;
function moveToPrevious()
{
  new Effect.Move('imageBoxInside', { x: 180, y: 0, transition: Effect.Transitions.sinoidal });
}  

function moveToNext()
{
  new Effect.Move('imageBoxInside', { x: -180, y: 0, transition: Effect.Transitions.sinoidal });
}
&lt;/script&gt;</code>
</pre>
<p><strong>Step 4.</strong> The only thing that remains is to connect everything together. We add a couple links to move call the next and previous functions defined above.</p>
<pre>
<code>&lt; a href="javascript:void(0);" href="javascript:void(0);" onclick="moveToPrevious(); return true;"&gt;&lt;img src="http://blogs.missiondata.com/wp-admin/images/previous.png" /&gt;</a>
&lt; a href="javascript:void(0);" href="javascript:void(0);" onclick="moveToNext(); return true;"&gt;&lt;img src="http://blogs.missiondata.com/wp-admin/images/next.png" /&gt;</a></code>
</pre>
<p>And that is all there is to it. See it in <a href="http://blogs.missiondata.com/examples/slide/example1.html">action</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.missiondata.com/blog/web-development/13/smooth-scrolling-image-list/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>No javascript detection</title>
		<link>http://www.missiondata.com/blog/web-development/11/no-javascript-detection/</link>
		<comments>http://www.missiondata.com/blog/web-development/11/no-javascript-detection/#comments</comments>
		<pubDate>Wed, 15 Feb 2006 20:08:44 +0000</pubDate>
		<dc:creator>carsonm</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blogs.missiondata.com/?p=11</guid>
		<description><![CDATA[Have you ever wondered what you can do if someone doesn&#8217;t have javascript turned on and it is needed on the page they are sitting at? Well here is the answer: &#60;html&#62; &#60;head&#62; &#60;noscript&#62;&#60;meta http-equiv="refresh" content="0; RL=nojscript.html"/&#62;&#60;/noscript&#62; &#60;/head&#62; &#60;body&#62; A javascript test. &#60;/body&#62; &#60;/html&#62; If the user doesn&#8217;t have javascript turned on they will be [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever wondered what you can do if someone doesn&#8217;t have javascript turned on and it is needed on the page they are sitting at? Well here is the answer:</p>
<pre><code>&lt;html&gt;
  &lt;head&gt;
    &lt;noscript&gt;&lt;meta http-equiv="refresh" content="0; RL=nojscript.html"/&gt;&lt;/noscript&gt;
  &lt;/head&gt;
  &lt;body&gt;
    A javascript test.
  &lt;/body&gt;
&lt;/html&gt;</code></pre>
<p>If the user doesn&#8217;t have javascript turned on they will be redirected to the page nojscript.html. It doesn&#8217;t work as well as having a page in between that does the detection but if you have to do it on the page you need the javascript on this is the way to go.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.missiondata.com/blog/web-development/11/no-javascript-detection/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

