Skip to main content

skip to main content

developerWorks  >  Web development  >

Exchanging information with a server without reloading your HTML page

Three techniques that can help you improve the efficiency of your Web application

developerWorks
Document options

Document options requiring JavaScript are not displayed


New site feature

Check out our new article design and features. Tell us what you think.


Rate this page

Help us improve this content


Level: Introductory

Tong Li (litong01@us.ibm.com), Software developer, IBM

01 Jan 2002

Does constant page reloading make your Web site a resource hog? Perhaps your applications are spending too much time communicating with the server, reloading the entire page when only part of it needs to be changed. This not only decreases Web performance, but also increases Web server workload and traffic between server and client. Fortunately, there are techniques you can employ to solve these problems. Here, developer Tong Li offers three such techniques.

Traditionally, one of the shortcomings of Web applications is the time they spend sending information to, and receiving information from, the application server. Most developers use a simple HTTP POST or GET method when pieces of information, such as a user ID or password, need to be sent to a Web server to be logged in. Since both POST and GET methods are HTTP requests, when either of these is sent, the page that submits the request will get replaced by whatever is returned from the server. So one way or another the page is changed.

If the wrong user ID or password is submitted for validation, chances are either the user will be redirected to a different page, or the login page will be reloaded and the user will be asked to enter the correct information. Both redirecting and reloading will cause the browser window to be redrawn. This article discusses several techniques you can use to avoid the reload effect and allow a Web client GUI to seamlessly exchange information with its server. In some cases, this can greatly reduce Web traffic.

For Web applications, there are basically two types of communications: one way and two way. With one-way communication, a client sends information to a server. The client does not expect any confirmation from that server, nor does it care whether the server processes the information appropriately. With two-way communication, the client sends information to the server and waits for confirmation. This confirmation can be as simple as a flag indicating success or failure, or as complex as a large set of data. Regardless of whether it is one-way or two-way communication between client and server, at its core it is an HTTP protocol. As explained above, both HTTP POST and GET requests (and thus both one-way and two-way communications) can cause reload problems if the Web pages are not carefully designed.

One-way communication reload

To solve the one-way communication reload problem, Web page authors can place an image tag in a page and do the following:

  • Set both the width and the height of the image to zero pixels
  • Give a name to the image tag

Whenever pieces of information need to be sent, the author can simply set a new URL to the image source attribute. Here is a snippet of the code:


Code inside the body tag

<img name="myimage" src="myimage.gif" width="0" height="0">



JavaScript code (anywhere in the page)

<script type="javascript">
var fakeId=0;
function sendInfo(data)
{
    fakeId += 1;
    document.images["myimage"].src = 
        escape("receiver.jsp?" + fakeId + "&" + data);
}
</script>

The parameter for function sendInfo should be a string and it should be constructed in key/value pair format. For example:

FirstName=John&LastName=Lee

In this example, we are sending a person's first name and last name to the server, and we want the information to be processed by a JSP file named receiver.jsp. This solution is especially useful if only small pieces of information need to be sent. Because this solution uses an HTTP GET method, the amount of the information that can be sent to the server is limited by the maximum length of a URL -- in most cases, 2048 bytes. When large data needs to be sent, you can divide the data into smaller sets and then call the function multiple times. You can use a transparent image for your page to make this solution more appealing. (Some browsers will show a non-transparent image as a dot even if the image sizes are set to zero.) The variable fakeId increases by 1 every time the function is called. This ensures that every URL assigned to the image source is different; the browser will not use the cached contents for the image source.



Back to top


Two-way communication reload

To solve the two-way communication reload problem, two solutions are available. Both solutions use the same JavaScript code, which can be found in exchanger.js. (To view the code, see Listing 1.) This code can be used without any modification; developers working with HTML can simply link the JavaScript file into their HTML pages to implement the solution. The basis of both solutions is the use of hidden <IFRAME> or <LAYER> tags. When communication between the client and server is necessary, you can use JavaScript to change the source of these tags. Since the <IFRAME> and <LAYER> tags are hidden and they are sized at 0 pixels tall and 0 pixels wide, the page that's seen by the user will not be reloaded. Rather, only select data is exchanged between the client and the server; the server will not resend or regenerate the whole page and the browser will not need to redraw the whole browser screen. This not only improves performance but decreases Web traffic as well.

Solution 1: A pure JavaScript implementation

This solution creates an <IFRAME> tag for Netscape 6 and Internet Explorer and a <LAYER> tag for Netscape 4.x, and sets the visibility attribute of the created tags to hidden. When data needs to be sent to a server, the source of the tag will be assigned a URL with parameters. The parameters should be constructed in key/value pairs. Anything returned for the request will also be in the frame or layer. Here is an example:


JavaScript code (anywhere in the page)

<SCRIPT LANGUAGE="JAVASCRIPT" src="exchanger.js"></SCRIPT>
<SCRIPT LANGUAGE="JAVASCRIPT">

var theBuffer;

//call this function in page onload event handler
function initialize()
{
  theBuffer = new exchanger();
}

//call this function when data needs to be sent to server
function sendDataToServer(data)
{
  theBuffer.sendData("receiver.jsp?" + data);
}

//call this function to check what the server returns.
function showReturnData()
{
  alert(theBuffer.retrieveData("myNewData"));
}
</SCRIPT>

Function initialize() should be called after an HTML page is loaded. In most cases, you can use it as the ONLOAD event handler. For example:

<BODY ONLOAD="initialize()">

This function creates an instance of the exchanger class, which is defined in the exchanger.js file, and assigns it to a global variable. When data needs to be sent, member function sendData() of exchanger class should be called as demonstrated in function sendDataToServer(). The data returned by the server is accessed by using member function retrieveData() of the exchanger class. Developers can use the data in any way that's appropriate for their applications. In function showReturnData(), function ALERT is simply used to show the retrieved data.

As you may find in function create in the exchanger.js file, this solution uses createElement to dynamically create <IFRAME> and <LAYER> elements for a document. If the target browser allows dynamic creation of HTML tags <IFRAME> or <LAYER>, this solution may be appropriate. As of the writing of this article, the solution can be used for Netscape 6, Netscape 4.x, IE, and Mozilla.

If the target browser does not allow dynamic creation of either <IFRAME> or <LAYER> tags, the following solution may satisfy your communication requirements.

Solution 2: A JavaScript and HTML tag implementation

Because some browsers do not support the createElement function call, the pure JavaScript solution cannot be used across all the target browsers. This second solution overcomes the reload problem by placing <IFRAME> and <LAYER> tags into the HTML document. The frame and layer need to be invisible and their sizes need to be set to 0 pixels tall and 0 pixels wide. After that, everything works exactly the same as the pure JavaScript solution. Here is an example:


JavaScript code (anywhere in the page)

<SCRIPT LANGUAGE="JAVASCRIPT" src="exchanger.js"></SCRIPT>
<SCRIPT LANGUAGE="JAVASCRIPT">

var theBuffer;

//call this function in page onload event handler
function initialize()
{
  theBuffer = new exchanger("myframe");
}

//call this function when data needs to be sent to server
function sendDataToServer(data)
{
  theBuffer.sendData("receiver.jsp?" + data);
}

//call this function to check what the server returns.
function showReturnData()
{
  alert(theBuffer.retrieveData("myNewData"));
}
</SCRIPT>



HTML code (between <BODY> and </BODY> tags)

<IFRAME name=myframe style="width:0;height:0">
<LAYER name=myframe WIDTH=0 HEIGHT=0 visibility="hide">
</LAYER>
</IFRAME>

To make these solutions work, a JSP file named receiver.jsp is used. The file does not have to be a JSP file. Any server-side script file that handles HTTP GET or POST requests can be used for this purpose. Here is the file used in this article:

<HTML>
<HEAD>
<%@ page import="java.util.*, java.text.*" %>
<%
   
//request.getParameter("whatever") can be used here to get data
//sent from the client.

//send server's date and time to client.
String currentTime = Calendar.getInstance().getTime().toString();

%>
<SCRIPT LANGUAGE="JAVASCRIPT">
var myNewData = "<%= currentTime %>"
//many other data can be sent back to client this way.
</SCRIPT>
</HEAD>
<BODY></BODY>
</HTML>



Back to top


Conclusion

Large Web pages can take a long time to reload when the information in those pages needs to be updated. This can increase Web traffic and Web server workloads. The techniques presented in this article can enable you to update a Web page without having to reload the entire page. All three techniques are based on the modification of the source attribute of the IMG, IFRAME, and LAYER tags. When you need to exchange information between the server and the client, you can modify the source attribute from the client so data can be sent and received without reloading the whole page. This ensures that only select data gets transferred over the Internet, thereby increasing Web performance while decreasing both Web traffic and server workloads.



Resources

  • Find out all about the Document Object Model (DOM) at the W3C site.

  • DevEdge offers a range of tools and information to help you develop your Web applications.

  • The W3C also includes an HTML page where you'll find pointers to HTML specifications and guidelines for using the markup language.

  • Planning for growth, from IBM's High Volume Web Site Team, can show you how your Web site can satisfy future demands and evaluate potential workload and infrastructure changes.

  • The developerWorks Web architecture topic offers a range of resources to help you create a dynamic, efficient Web presence.

  • The IBM Patterns for e-business site features a number of reusable assets that can help speed the process of developing applications.


About the author

Tong Li received an M.S. in computer science from University of Alabama in 1996. He has worked as a programmer and advisory software engineer since 1988. His interests are in J2EE, portal server, CORBA, and project management. You can contact him at litong01@us.ibm.com.




Rate this page


Please take a moment to complete this form to help us better serve you.



 


 


Not
useful
Extremely
useful
 


Share this....

digg Digg this story del.icio.us del.icio.us Slashdot Slashdot it!



Back to top