Sunday, September 28, 2008

Simple Practice to Employ AJAX

This post presents a very simple method to employ AJAX. You would see how AJAX can update the content of your web pages without refreshing the entire pages.
Follow the steps below to create a simple AJAX project (in ASP.NET & C#):

Step 1. Create a Website in Visual Studio 2005/2008.

Step 2. Download the AJAX library here for this practice. And add it as a reference to your Website.

Step 3. In the <system.web> of your web.config file, add the following httpHandlers tag:




<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>


Step 4. In the Page_Load of your ASP.NET page write:
Ajax.Utility.RegisterTypeForAjax(typeof(class_name));
where class_name is the name of the class of your ASP.NET page; e.g. for the page "Default.aspx", class_name would be: Default and you would write:
Ajax.Utility.RegisterTypeForAjax(typeof(Default));
Step 5. In your class add an AJAX method. An AJAX method may be written as follows:
[Ajax.AjaxMethodAttribute(HttpSessionStateRequirement.ReadWrite)]
public object ReadDataFromMyDatabase()
{
return GetData();
// GetData is a regular method to retrieve
// data from your database
}


Step 6. In the html source of your page write a JavaScript function to call your AJAX method; e.g.:
<script language="javascript" type="text/javascript">
function ReadDataFromMyDatabase(){
Default.ReadDataFromMyDatabase(ReadDataFromMyDatabase_CallBack);
}

</script>
Step 7. Your JavaScript function requires a JavaScript Call Back function that will receive data from your AJAX method:

<script language="javascript" type="text/javascript">
function
GetCounts_CallBack(data) {

var
myData = data.value;

// Use your data; e.g.:

document.getElementByID("text1").value = myData;
}


</script>






No comments:

Post a Comment