AJAX IN ASP.NET






1.39/5 (9 votes)
Nov 4, 2007
6 min read

44022

89
The article show how to implementi AJAX in Asp.Net using XMLHttpRequest Object
Introduction
In all web application when you submit a button or sending a data to server the server each time deliver to you a new webpage.
What if I want just only a part of the webpage to be process and in this part get back another webpage content without reloading the whole page? How I can display data from another webpage in a DIV HTML element in the current page without loading the entire page.
Note: To read this article you must understand:
-
HTML / XHTML
-
JavaScript
What is Ajax?
Ajax is not an invention or a new programming language, it's a web development technique Which build based on old ones (JavaScript, XML, HTML, CSS). Ajax is stand for (asynchronous java script and XML), and this technique make your web site more flexible faster friendly and more interactive, Ajax became popular in 2005 when Google use this new technology.
What Ajax Can Do?
What if I want just only a part of the webpage to be process and in this part get back only what the client needs without reloading the hole page ?!!
This is what Ajax can do, with Ajax java script can communicate with server using XMLHttpRequest Object, and can exchange data with server. when you want to get or send data from server using JavaScript we make a form and post this data but unfortunately its reload anew web page with http request now we can get data from server behind the seen without reload the webpage, he will stay in the current page and will not notice any thing happened behind the seen.
A Simple Ajax JS method
Regardless of what you will do using Ajax, they all rely on the same basic functions, here I am using a function called: ajaxpage(URL, ContainerID), witch take the URL of the destination page that we want to display in the current page, and take the ID of the container where we will display the destination page in the current webpage – in our example is the DIV- and this function will do all the job to retrieve the page and display it using the XMLHttpRequest.
I will explain in brief what the function do enables you to easily use Ajax on your site to send "Get" or "Post" requests asynchronously and I will provide you with some URLS where you can understand and find more information about using this object.
Here the javasript file Ajax.js
ajaxpage()
var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http:///">http://"+window.location.hostname
var bustcacheparameter=""
function ajaxpage(url, containerid)
{
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari, Firefox, Opera 8.0+, Safari
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) // ifInternet Explorer\
{
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e)
{
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
document.getElementById(containerid).innerHTML=loadstatustext
page_request.onreadystatechange=function()
{
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState != 4)
{return;}
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
//alert(page_request.responseText)
}
What is this methods do?
We create a variable page_request to hold the XMLHttpRequest object. Then try to create the object with XMLHttp=new XMLHttpRequest (). This is for the Firefox, Opera, and Safari browsers. If that fails, try xmlHttp=new ActiveXObject ("Msxml2.XMLHTTP") which is for Internet Explorer 6.0, I think you can figure out what the rest is doing.
Note: This code above is work with the most browsers. The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed if (page_request.readyState != 4) //requset is Completed The data sent back from the server can be retrieved with the responseText property we retrieve using this code: document.getElementById(containerid).innerHTML=page_request.responseText; The open () method takes three parameters; the first defines which method to use when sending the request (GET or POST). The second specifies the URL of the server-side script. The third specifies that the request should be handled asynchronously. The send () method sends the request off to the server.
Include the Ajax file ajax.js in you application witch contain the function we will call. Include a picture Loading.gif in the images folder witch will be shown while the page being requested. Create tow pages witch we will called from another page/page ajaxpage1.aspx and ajaxpage2.aspx the two destination file. Create a display page display.aspx were we will call the other 2 pages When creating the page ajaxpage1.aspx we remove all html elements-except the page directive- and simply put a div and write inside it "this is the Ajaxpage1" and simply does in the second page the same but write inside it " this is the ajaxpage2", so we can know witch page we are calling.
This how the HTML page will look like: In the display.aspx page we will call the other 2pages using the function that u see above in the ajax.js file. We create a DIV and give it ID="Main1" this container where the other page will be displayed, and we put two buttons button1 will call the AjaxPage1.aspx and button2 will call the ajaxpage2.aspx and after the page directive we will put the following code: The onreadystatechange Property
The responseText Property
Sending a Request to the Server
How to Use this method:
Destination HTML Page
<%@ Page Language="C#" AutoEventWireup="true"CodeFile="ajaxpage1.aspx.cs" Inherits="_Default" %>
<div style="width: 100px; height: 100px">
this is the first page
</div>
<script src="ajax.js"></script>
<script>
var loadstatustext=" <img src='images/loading.gif' /><Font Class='Content'> جارى التحميل </font>";
function Page1()
{
var links="AjaxPage1.aspx";
var container1="Main1";
ajaxpage(links,container1);
}
function page2()
{
var links="AjaxPage2.aspx";
var container1="Main1";
ajaxpage(links,container1);
}
</script>
as you can see the first script called the ajax.js file and then we have a variable called loadstatustext witch is the GIF image that will be displayed while the page been requested, and then in function page1 () we define a variable Links witch is the desired webpage that will be displayed in the current page, and another variable called container1 where we want the page to be displayed and here I give it the id of the DIV where I want the data to be displayed.
Then we want to register the script to the two buttons so double click in the button1 that will create the click events handler and put this code to lunch the function page1()
protected void Button1_Click(object sender, EventArgs e)
{
Page.RegisterStartupScript("StartUp", "<script>page1( );</script>");
}
And do the same with button2 to lunch the function page2()
When run the display.aspx and press the button1 it will displayed
This is first the Ajax page1!!
And when press the button2 it will displayed
This is the second Ajax page1!
And you can notice the loadin.gif image while process.
Conclusion
In This article I want to show how you can use AJAX technology in ASP.NET application in simple way .Ajax is a new technology and its worth to be used in your website I think you have now along road to do all what is coming to your when you know what this technology can do very easily. Thank you for reading my article you will find a source code with the article witch contains all the files I mention here and you can run it easily and I am waiting for your comment: D.
References: