Weird Thoughts From Eric's Head

Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

Sending XML to the Sever with AJAX
A question that has come up to lately by people on JavaRanch and emails I received is how do I send an XML to the server using Ajax. It is possible to send an XML document in the request parameter. One thing you need to make sure is that you set the header correctly to text/xml and post the document to the server. This following is a basic example that highlights the fact that we are not limited to just sending query string and form values to the server, which seems to be implanted into certain developer’s minds.

Read more...

A Basic Ajax Content Management Framework
One of the projects that I just took control of tracks documents that the Webmaster is placing manually into a folder and pastes a separate URL into a database so it can be linked to multiple records, other tables, and other crap. That part is not important, but I thought I would tell you where I thought of this. As I was coding the checking to see if a file exists I was like man, Ajax could be the missing link to those web content management tools out there. You have a site builder like on Brinkster or any of the other host and Ajax can improve its effectiveness. I was always annoyed by how slow they were to react when navigating since it always had to do the full-page refresh to get the documents and such. If you had to go 10 files deep in the tree, I needed a beer and a bag of pretzels waiting for it to happen.

So I just made a quick vb.net project that is not fancy. It is a basic framework for you to be able to navigate through a directory on a web server and look at the files and folders. The code is a basic starting point for anyone that wants to create a way for a user to look for files on the server. I see a lot of people saying that they want a file input to be able to search the server. With this code, you can create it. If I had more time, I would create a look like file browser, but I am busy with the book! If anyone out there does it, make sure to post a link in the comments.

Now, you really need to address security here since you are allowing people to access the folder structure on the server! I did a very(infite+1) small check that I am sure could be bypassed. If anyone has some good ideas on security for this, lets us know!

The code here does three things:

  1. Creates a Breadcrumb Navigation
  2. Lists the Folders
  3. Lists the Files
Make sure to keep reading this to see the code. People complained I do not use an Excerpt, so now I am using one!

Read more...

Remember a Div's Scroll Position
A person asked the question on how to remember a div's scroll position on the page when the comes back to the page. It is rather easy to do and it involves a session cookie to remember the position. Yeah, the cookie part could be done better so do not comment on that! I went the easy route!

<html>
  <head>
    <title>Fun Scroll</title>
    <style type="text/css">
      #divTest{width:150px;height:200px;overflow:auto}
    </style>
    <script type="text/javascript">
      window.onload = function(){
        var strCook = document.cookie;
        if(strCook.indexOf("!~")!=0){
          var intS = strCook.indexOf("!~");
          var intE = strCook.indexOf("~!");
          var strPos = strCook.substring(intS+2,intE);
          document.getElementById("divTest").scrollTop = strPos;
        }
      }
      function SetDivPosition(){
        var intY = document.getElementById("divTest").scrollTop;
        document.title = intY;
        document.cookie = "yPos=!~" + intY + "~!";
      }
    </script>
  </head>
  <body>
    <div id="divTest" onscroll="SetDivPosition()">
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      ERIC<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
      1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>1<br/>
    </div>
  </body>
</html>
Hope it helps,

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages
Co-Author of Ajax In Action

Ajax In Action - November 2005

If you have been following my blog lately, you should know that I have been working on Ajax In Action with Manning and a co-author Dave Crane.

I personally wrote all of the example projects in the book. The projects give you a step by step process of integrating AJAX into an application in order to create a Rich User Interface. For those of you that are afraid of DHTML, do not worry! I explained the cross browser differences that cause people to bang their heads against the wall for years. You should have no problem taking these examples and integrating them into your applications so your Web applications start to look and feel like a client application.

Every project in the book looks at the flaws and benefits of the classical solution and the AJAX solution. I also talk about AJAX implementations that are out there. I look at the benefits the application has and what mistakes people have implemented. Too many calls to the server can easily drain your resources if you are not careful.

The release date for Ajax In Action is scheduled for November 2005 and you can read more about the book here.

"What makes this worthy of a book?"

I have been asked this question almost 10 times a day by people. The people that ask it tend to think that AJAX is hype or that there are plenty of examples out there. The fact is, there is not a lot of centralized data on the subject. You need to go from blog to blog and Web site to Web site to get a grasp on the data. You can get bad examples and you can get good examples. This book looks at AJAX from the concept to real world projects that investigates both the good and the bad.

A lot of developers have a hard time coding a single line of JavaScript. I have seen this first hand in the industry. AJAX is based on JavaScript, so developers need something that talks at AJAX at a high level and also explains the entire ClientSide code. Most of the blogs and Web sites do not explain the core code and leaves developers scratching their head. AJAX in Action will allow a developer learn about AJAX from the ground up. They will be able to take the examples from the book and apply it to their applications to increase the performance of their users.



Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Update User's Session with AJAX
[edit]Make sure to look at the new version of the script here: Round 2 version[/edit]
Well I am a little behind on my blogging here! Well I said I was going to do another AJAX example so here we go.

On some applications I help to develop, users were complaining that they were getting timed out of the application. I have no idea what they were doing on a single page for 30 minutes, but they complained. I guess they should not take that phone call!

Anyway we needed a solution to notify the user they were about to be timed out without posting back the page. Well since I am writing Ajax in Action, I proposed an Ajax solution. The Ajax solution keeps us from posting back the page to the server or opening up a pop up windw. Both methods have there flaws since the post back method can loose data if we happended to mis a viewstate field and the pop up window may be blocked by a pop up blocker. You can never be sure that the pop up would get through.

So I came up with a little script that uses AJAX to call a server side page. The server side, when called, updates our session. So the code for the server is only a few lines.

Select your language so you see the right code!



VB.NET code
Now with a .net page, we need to remove all but the code behind reference from our aspx page. In this case I called the page sessionUpdater.aspx.

<%@ Page Language="vb" AutoEventWireup="false" 
Codebehind="sessionUpdater.aspx.vb" Inherits="TestAJAX.sessionUpdater"%>
The code behind then just sets the content type of the page and then outputs a string with the time stamp within the Page_Load.
Private Sub Page_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
    Response.ContentType = "text/xml"
    Response.Write("Session Updated - Server Time: " & DateTime.Now.ToString)
End Sub
Then we have the Client Side code. To make this easy we can use an external JavaScript file so we need to link to it in our page.
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="sessionTimeout.aspx.vb" Inherits="TestAJAX.sessionTimeout"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>sessionTimeout</title>
    <script type="text/javascript" src="SessionWarningTimer.js"></script>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
    <</form>
  </body>
</html>
Then we have our external JavaScript file (SessionWarningTimer.js):
var reqXML;
    
function LoadXMLDoc(url){ 
  if (window.XMLHttpRequest){ //Mozilla, Firefox, Opera 8.01, Safari
    reqXML = new XMLHttpRequest(); 
    reqXML.onreadystatechange = BuildXMLResults; 
    reqXML.open("GET", url, true); 
    reqXML.send(null); 
  }
  else if(window.ActiveXObject){ //IE
    reqXML = new ActiveXObject("Microsoft.XMLHTTP"); 
    if (reqXML) { 
      reqXML.onreadystatechange = BuildXMLResults; 
      reqXML.open("GET", url, true); 
      reqXML.send(); 
    } 
  }
  else{ //Older Browsers
    alert("Your Browser does not support Ajax!");
  }
} 

function BuildXMLResults(){
  if(reqXML.readyState == 4){ //completed state
    if(reqXML.status == 200){ //We got a sucess page back
         
      //Check to verify the message from the server 
      if(reqXML.responseText.indexOf("Session Updated - Server Time:") == 0){
        window.status = reqXML.responseText; //display the message in the status bar
        SetTimer(); //restart timer
      }
      else{
        //display that that session expired
        alert("Your session appears to have expired. You may loose your current data.");
      }
    } 
    else{
      //display server code not be accessed
      alert("There was a problem retrieving the XML data:\n" + reqXML.statusText);
    }		
  }
}
      
function ConfirmUpdate(){
  //Ask them to extend
  if(confirm("Your session is about to expire. Press 'OK' to renew your session.")){
    //load server side page if ok
    LoadXMLDoc('sessionUpdater.aspx'); 
  }
}      
      
var timerObj;
function SetTimer(){
  //How long before timeout (should be a few minutes before your server's timeout
  var dblMinutes = .2;
  //set timer to call function to confirm update 
  timerObj = setTimeout("ConfirmUpdate()",1000*60*dblMinutes);
}
      
//start the timer
SetTimer();
JSP code
We need to set the content type and return a string with a timestamp back to the client.
<%@ page contentType="text/xml"%>
Session Updated - Server Time: <%= new java.util.Date() %>
Then we have the Client Side code. To make this easy we can use an external JavaScript file so we need to link to it in our page.
<html>
  <head>
    <title>sessionTimeout</title>
    <script type="text/javascript" src="SessionWarningTimer.js"></script>
  </head>
  <body>
    <form id="Form1" method="post">
    </form>
  </body>
</html>
Then we have our external JavaScript file (SessionWarningTimer.js):
var reqXML;
    
function LoadXMLDoc(url){ 
  if (window.XMLHttpRequest){ //Mozilla, Firefox, Opera 8.01, Safari
    reqXML = new XMLHttpRequest(); 
    reqXML.onreadystatechange = BuildXMLResults; 
    reqXML.open("GET", url, true); 
    reqXML.send(null); 
  }
  else if(window.ActiveXObject){ //IE
    reqXML = new ActiveXObject("Microsoft.XMLHTTP"); 
    if (reqXML) { 
      reqXML.onreadystatechange = BuildXMLResults; 
      reqXML.open("GET", url, true); 
      reqXML.send(); 
    } 
  }
  else{ //Older Browsers
    alert("Your Browser does not support Ajax!");
  }
} 

function BuildXMLResults(){
  if(reqXML.readyState == 4){ //completed state
    if(reqXML.status == 200){ //We got a sucess page back
         
      //Check to verify the message from the server 
      if(reqXML.responseText.indexOf("Session Updated - Server Time:") == 0){
        window.status = reqXML.responseText; //display the message in the status bar
        SetTimer(); //restart timer
      }
      else{
        //display that that session expired
        alert("Your session appears to have expired. You may loose your current data.");
      }
    } 
    else{
      //display server code not be accessed
      alert("There was a problem retrieving the XML data:\n" + reqXML.statusText);
    }		
  }
}
      
function ConfirmUpdate(){
  //Ask them to extend
  if(confirm("Your session is about to expire. Press 'OK' to renew your session.")){
    //load server side page if ok
    LoadXMLDoc('sessionUpdater.jsp'); 
  }
}      
      
var timerObj;
function SetTimer(){
  //How long before timeout (should be a few minutes before your server's timeout
  var dblMinutes = .2;
  //set timer to call function to confirm update 
  timerObj = setTimeout("ConfirmUpdate()",1000*60*dblMinutes);
}
      
//start the timer
SetTimer();
Save it, then we can test this out.

Open up the page and wait until you get the warning.
confirm image

Then click the ok button
timestamp image

You can see that in the status bar, we have the time form our server showing we got the data from the server. Hopefully this shows you how easy it was to send a response to the server, retrieve its value, and display it on the screen.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages
Co-Author of: Ajax in Action