Click here to Skip to main content
15,885,132 members
Articles / Web Development / HTML

Salajax: Simple Ajax Library Solving Back Button and Bookmarks for Ajax Web Applications

Rate me:
Please Sign up or sign in to vote.
4.53/5 (10 votes)
11 Jul 2007CPOL4 min read 125.6K   1.3K   55  
An article on AJAX [Asynchronous JavaScript and XML], providing back button and bookmark functionality in a simplified class. Written in JavaScript, demonstrated in ASP.NET and can be used with any server-side scripting language.
<%@ Page language="c#" Inherits="AjaxTest.WebForm1" CodeFile="AjaxExample.aspx.cs" Trace="false" enableEventValidation="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 

<html>
  <head>
    <title>WebForm1</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name=vs_defaultClientScript content="JavaScript">
    <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">

          
    <script language="javascript" src="salajax.js">
    </script>
    
    
      <script language="javascript">
   
    var TestOnStart = function()
    {
        if(sal.Debug >= 2)
        {
            alert("OnStart triggered");
        }
    }
    
    var TestOnEnd = function()
    {
        if(sal.Debug >= 2)
        {
            alert("OnEnd triggered");
        }
    }
       
    //set up the salajax settings.
    var sal = new salajax();
    sal.Debug = 0;
    sal.EnableBackButton(true); //turns on the back buttons.
    sal.EnableBookmarks(true); //saves state in the clients cookies so bookmarks will work provided they havn't deleted their cookies.
   
   
    sal.OnStart = 'TestOnStart()'; //enables a script to run before the request is made. e.g. change pointer/icon/loading section of page.
    sal.OnEnd = 'TestOnEnd()'; //enables a script to run after the request is returned. e.g. change pointer/icon/loading section of page.
    
    sal.PresendHtml = '<img border="0" src="http://www.ajaxload.info/cache/ff/ff/ff/00/80/ff/24-1.gif"/>';
    sal.OnError = 'DefaultOnError()';//set a function to pass if there is an error.
    sal.OnErrorHtml = '<img border="0" src="http://www.register.com/images/icons/error_icon.gif" /><font color="red">Error!</font>'; //When setting InnerHtml and there is an error this will be displayed.
    sal.EvalScripts = true; //if set to true, will evaluate any javascript in the responseText. 
                             //NOTE: to override functions you must declare the functions in your ajax response like this:
                             //         var FunctionToChange = function(var1,var2)
                             //         { 
                             //             //do stuff
                             //         }
                             
    this.KeepDotNetViewState = true; //if set to true will post the current viewstate when using .NET
    //end setting the salajax settings.
    
    
    
    
    //Called by body.onload to populate the select box with data from the server.
    function InitData(){
			SetInnerHTMLFromAjaxResponse('?button=6','cust_select_div');
    }
    
    //Adds name to the request to the Ajax request.
    //uses the PassAjaxResponseToFunction(url,callbackFunction) function.
    //Note: we could have just written onchange="PassAjaxResponseToFunction("?button=5&name="+this.value, 'FindCustomerCallBack')
    //in the select box(what select box? the one in created in InitData() from the .cs file), but I wanted to show that you can call this from within a function. (you may need more parameters to pass to the url).
    function FindCustomer(){
			var name = document.getElementById("cust_select").value;
			if(name != ""){
				sal.PassAjaxResponseToFunction("AjaxExample.aspx?button=5&name="+name, 'FindCustomerCallBack');
			}
    }
    
    //split the response string into its different values and populate the table divs..
    function FindCustomerCallBack(r)
    {
      //we are expecting something like '1;nigel;liefink;27' as a response.
			var s = r.split(';');
			for(var i=0;i<s.length;i++)
			{
			  //populate the data divs.
				document.getElementById("cust_"+i).innerHTML = s[i];	
			}
    }
    
  
    </script>
    
  </head>
  <body onload="javascript:InitData();">
  

  
  
    <form id="Form1" method="post" runat="server">
    
    
    <h1>Test the Ajax way.</h1>
    
    <h2>Example 1 - Simple Ajax calls</h2>
    
    <p>These buttons that will fetch dynamic data from the server without the need to re-fetch the whole page as per normal html request/response.</p>
    <p>Interesting to note that the LongAjaxCall button freezes all other ajax calls until its process has finished. If threading were possible in javascript, this could be fixed.<br>
       If anyone can figure out how to stop this behaviour, be sure to let me know.</p>
    <!-- 
    SetInnerHTMLFromAjaxResponse is a javascript function contained in ajax.js.
    -->
    <input type="button" onclick="sal.SetInnerHTMLFromAjaxResponse('AjaxExample.aspx?button=1&extra=hello','r1')" value = "GetASPLabel" />
    <input type="button" onclick="sal.SetInnerHTMLFromAjaxResponse('AjaxExample.aspx?button=2','r2')" value = "GetDataTable" />
    <input type="button" onclick="sal.SetInnerHTMLFromAjaxResponse('AjaxExample.aspx?button=3','r1')" value = "GetDropDownList" />
    <input type="button" onclick="sal.SetInnerHTMLFromAjaxResponse('AjaxExample.aspx?button=4','r2')" value = "LongAjaxCall" />
    
    <table border="1" cellpadding="0" cellspacing="0"><tr><td> <div id="r1"></div> </td><td> <div id="r2"></div> </td></tr></table>
   
   <hr/>
   
		<H2>Example 2 - Select box refresh</H2>
		<p>
		Select a customer to look up their details from the database.
		</p>
		
		<!-- this select box is populated from the database and created on the server. 
				 (see the aspx.cs file and the javascript InitData() function in this file.) -->
		<div id="cust_select_div"></div>

		<table border=1 width="50%">
			<tr><td>id</td><td>Name</td><td>Surname</td><td>Age</td></tr>
			<tr>
				<td><div id="cust_0"></div></td>
				<td><div id="cust_1"></div></td>
				<td><div id="cust_2"></div></td>
				<td><div id="cust_3"></div></td>
			</tr>
		</table>
		
		<hr/>
		
		
		<h2>
		Example 3 - Filter on key up event.
		</h2>
		<p>
		Data is continually refreshed from the server on key up event. the result is a rendered datagrid returned from the server.
		</p>
		Enter a minimum age: <input type="text" size="3" id="min_age" onkeyup="sal.SetInnerHTMLFromAjaxResponse('?button=7&min='+this.value,'cust_dg_div')" /><br/>
		<div id="cust_dg_div"></div>
		
		
		<h2>
		Example 4 - Submit form and keep view state.
		</h2>
		
		<asp:TextBox RUNAT="SERVER" ID="aspTextBox" Text="Enter new text for label" EnableViewState="true" />
		<asp:HiddenField runat="server" ID="button" value="9" />
		<asp:DropDownList runat="server" ID="aspDropDownList" />
		
		<div id="testviewstate" >
		    <asp:Label ID="aspLabel" RUNAT="SERVER" Text="Test The View State"/>  
		</div>
		
		<input type="submit" onclick="sal.SetInnerHTMLFromAjaxResponse('form','testviewstate');return false;" value="Test"/>

		
		
		
    </form>
    
    <h2>
    Example 4 - Testing submission of form
    </h2>
    
    <form id="testformid" action="?button=8">
        Name: <input type="text" id="name" value="" />
        Age: <input type="text" id="age" value="" />
        <input type="submit" onclick="sal.SetInnerHTMLFromAjaxResponse(this.form,'testformdiv');return false;" />
        <div id="testformdiv" ></div>
    </form>
    
  </body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions