Skip to main content

AJAX CALLBACK USING HTTP

In this AJAX Tutorial i will try to explain "What is AJAX" & how you can start to learn AJAX from very basic. Ajax means Asynchronous JavaScript and XML. Asynchronous means that when you send a request, you wait for the response to come back, but are free to do other things while you wait. Ajax is not a new technology but in these days we found it in a new way. Currently almost all developers want to implement Ajax functionality to achieve asynchronus call back. ASP.NET gives us huge facility to implement Ajax functionality by using ScriptManager and UpdatePanel within very short time. But in this tutorial i will discuss Ajax basics menas XMLHttpRequest which is the generic HTTP client for JavaScript. To explain here i am using an example which described how to call server side aspx page using javascript. The serverside aspx page gives us the current server time & we will display the time into the page using Ajax.

Output Looks Like:


To implement the example add two page into your project. The first one contains the javascript code to call the second page using Ajax. And the second page returns server date time. You cab set any name for the first page but set the name for second aspx page is "ReceiveAjaxCall.aspx". Because we will call this page using the page name from javascript Ajax method.

Steps to call a serverside page by javascript using AJAX:
1. Declare an XMLHttpRequest object.
2. Instantiate the object.
3. Write a function to receive server side data
4. Make a call to server asynchronusly
5. Send


If you follow my code examples of first page then will get all steps one by one. The HTML markup code for first page is given below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ajax1jscriptcalling.aspx.cs" Inherits="ajax1jscriptcalling" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>XMLHTTP Test</title>

<script language="javascript" type="text/javascript">


function CallAjaxFunction()
{
var AjaxObject;

try
{
// For Other Browsers Like Opera, Mozilla Firefox, Safari
AjaxObject = new XMLHttpRequest();
}
catch (e)
{
// For Internet Explorer
try
{
AjaxObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
AjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something might wrong here
alert("Your browser does not spport XMLHTTP request!");
return false;
}
}
}

// Create a function that will receive data sent from the server
AjaxObject.onreadystatechange = function()
{
if(AjaxObject.readyState == 4) // Response came / server side processing completed
{
document.getElementById('<%= lblTime.ClientID %>').innerHTML='Current Server Date Time is: '+AjaxObject.responseText;
}
}
AjaxObject.open("GET", "ReceiveAjaxCall.aspx", true);
AjaxObject.send(null);
}
</script>

</head>


<body>
<form id="form1" runat="server">
<div>
<label runat="server" id="lblTime" style="font-family:Tahoma;font-weight:bold;color:Blue;font-size:1.2em"></label>
<br />
<br />
<asp:Button runat="server" id="cmd" OnClientClick="CallAjaxFunction(); return false;" Text="Get Server Time (Server Side Button)" />
<input type="button" onclick="CallAjaxFunction();" value="Get Server Time (HTML Button)" />
</div>
</form>
</body>


</html>

Look the difference between IE & non IE browsers ajax object instantiation block. Otherwise your page will not support cross-browser. If you look at the onreadystatechange property then you found that here i have declared a fixed value 4 to determine that the server call is completed. Yes 4 denotes that "The request is complete". Onreadystatechange has another 4 values like 0,1,2,3 denotes "The request is not initialized", "The request has been set up", "The request has been sent", "The request is in process" respectively. But we need to check only 4. When we get the value 4 then we write the server return value into our page label.

The open method is used to set the request type (GET, POST, PUT, or PROPFIND), the URL of the page being requested, and whether the call will be asynchronous or not. The basic syntax for open method is given below:

open(type,url,isAsync,username,password)

where username, password is optional.

And the the send method makes the connection to the URL specified in open.

To write the datetime in the page i added a lblTime label control and to make postback to the server i added two buttons one is HTML button & another one is server side button control.

OK now our receving data part is completed. We will go to implement second page which is called by first page through javascript XMLHttpRequest. Since we will send simple date time, just write the below codes into the page load event.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Clear();
Response.Write(DateTime.Now);
Response.End();
}
}

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour

Add Edit Update Records in GridView using Modal Popup in ASP.Net

Add Edit Update Records in GridView using Modal Popup in ASP.Net In this article, I’ll explain how to Add and Edit records in ASP.Net GridView control using ASP.Net AJAX Control Toolkit Modal Popup Extender. Database For this tutorial, I am using Microsoft’s NorthWind database. You can download it using the following link. Download Northwind Database Connection string Below is the connection string to connect to the database. < connectionStrings >     < add name = " conString "      connectionString = " Data Source=.\SQLExpress;database=Northwind;     Integrated Security=true " /> </ connectionStrings >   HTML Markup Below is the HTML Markup of the page. Below you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with a Modal Popup Extender that will be used to Add or Edit the records in the GridView