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        {     ...

Hierarchical GridView in ASP.NET with AJAX, JQuery implementation - Part 1

Previously I had blogged some post related to showing two grids in hierarchical way. For example - when I need to show an invoice reports on the screen, the user requesting to show the list of invoices at initial time and they can drill down the details of item details of each invoice by clicking on respective row. The implementations can be in multiple ways, but I had blogged the implementation with AJAX and without AJAX using Java script on ASP.NET page. Below are the URLs of the same – Hierarchical GridView in ASP.NET Hierarchical GridView in ASP.NET with AJAX, Javascript implementation In this post I am taking the same requirements done before and enhance with some additional functionality as per readers expectations. The requirement on this implementation will be – The page should show a Grid View with list of Orders with Expand icon on the first column. On click of expand icon on each row, the Order Details of the Order must be fetched from the database ...

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to ...