AJAX, ‘Old wine in a new bottle’. Puzzled!  Absolutely right. AJAX was with us for a long time, until we realized its true potentials. Lets take a very close example and we use it in our everyday life. Google? Yes, very true. Google was very early mover in AJAX arena and showed the world, web applications close to desktop applications. People were so fascinated with desktop applications that there was an urgent need of such ‘Avatar’.  Suppose you are in the middle of filling a user registration page. You fill all the necessary information and hit the register button. Err..it says “Username already exists. Please try again”. You tried once, twice, thrice and so many times and after page refreshes it is showing the same message. Well, application does not have any choice but to display this error message. But now we can take off the pain and show something interactive, a user may like. Major websites will allow you to enter the username, but at the same time they will be able to tell you if this username has been taken out and without page refresh. That is AJAX. Most close example. Try typing words in Google search box and it will show you an array of suggestions. This is just a tip of iceberg. Believe me, you can create a very rich web based application by allowing AJAX to come into your life.
Topics We Will Cover
(1)    What is AJAX
(2)    Why to use AJAX
(3)    AJAX nomenclatures
(4)    AJAX with ASP.NET 4.0 (.NET 4.0 framework is still in beta but a lot to offer)
(5)    Future of AJAX  
At the end of the post , you will find the link to download the code for all the examples demonstrated here.
What is AJAX
AJAX = Asynchronous JavaScript and XML.
It is based on JavaScript and HTTP requests.
You may ask, is this a new programming language? No, it is a new way to use existing standards.  It is a way of creating better, faster and more interactive web applications. AJAXcan directly communicates to the server and without page refresh.  It uses asynchronous data transfer (we say it, HTTP requests) between the browser and web server.  In this tutorial, we will create an application with AJAX support on .NET 4.0 (it is still in beta but a lot to offer). AJAX is all about making rich and user friendly web applications.
Why to use AJAX
I am sure, after reading the reasons; you will definitely plan to use AJAX in your web applications. Let’s take a very conventional example of submitting a form to the web server or getting the information of the submitted data.  In the conventional scenario, you fill some form, validate the inputs and submit the form. We wait for the server to respond and new page to load. This way application may run slowly and will have less use friendly experience. Now integrate our ‘Avatar’ in our web application. Our new ‘Avatar’ will directly talk with the server and process the information in the background and it is too fast.  With AJAX we can make or get the request from the server without page reload. AJAX was made popular by Google with its Google suggestion box.  In this tutorial we will develop Google suggestion sort of thing and I am sure once you finish with this tutorial, you will have every reason to use AJAX in your web applications.
AJAX Nomenclature
AJAX use the XMLHttpRequest object. By using the XMLHttpRequest object, we can update a page with data from the server after the page has loaded.  ‘Google Suggest’ is using the XMLHttpRequest object to create a very dynamic web experience. When we start typing in Google’s search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. And good news is The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).  XMLHttpRequest is the core of making AJAX web applications. Let’s examine how it works. Before we move ahead, I expect you are familiar with basic HTML and Javascript. Since AJAX is written in javascript, so have a look at the basic example, how it communicate with the server.
(1)    <head>
(2)    <script>
(3)    function loadXMLDoc(url)
(4)    {
(5)    if (window.XMLHttpRequest)
(6)    {// code for IE7+, Firefox, Chrome, Opera, Safari
(7)    xmlhttp=new XMLHttpRequest();
(8)    }
(9)    else
(10){// code for IE6, IE5
(11)xmlhttp=new ActiveXObject(”Microsoft.XMLHTTP”);
(12)}
(13)xmlhttp.open(”GET”,url,false);
(14)xmlhttp.send(null);
(15)document.getElementById(’suggestion’).innerHTML=xmlhttp.responseText;
(16)}
(17)</script>
(18)</head>
That’s all we needed to communicate with the server. Now server will obey our instructions and will respond t our requests.  Now let’s understand the above code. As I said earlier, core is XMLHttpRequest and it comes in built with the modern browsers.
Line 3 is very simple approach to pass an URL with javascript function loadXMLDoc.
Line 5 detects the browser is being used. There is some tweak, how it behaves with IE7+, Firefox, Chrome, Opera and Safari browser and with IE6 and IE5.  Nothing fancy.
Line 7 and 9, create and initializes the XMLHttpRequest  object.
Line 13 open() method takes 3 parameters. First one is the type of communication we want to perform with web server. So if you want to get some data from web server, use ‘GET’ else use ‘POST’.  Second parameter takes the server URL to whom you want to communicate. The third parameter  specifies, if the request should be handled asynchronously. You will stop by and ask, ‘Hey what dose it mean?’. Well, it can have two values. Either true or false.  False tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed.  For small applications and simple server request, this seems to be ok. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop.  Using True, the third parameter, you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent.  And since we cannot simply start using the response from the server request before we are sure the request has been completed, we need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion.  In this onreadystatechange function we test the readyState property before we can use the result of the server call. So, lets make a slight modification to our above code.
<head>
<script type=”text/javascript”>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{document.getElementById(’suggestion’).innerHTML=xmlhttp.responseText}
}
xmlhttp.open(”GET”,url,true);
xmlhttp.send(null);
document.getElementById(’suggestion’).innerHTML=xmlhttp.responseText;
}
</script>
</head>
Another question, what this readyState is? Well, this property holds the status of the server’s response.
State     Description
0              The request is not initialized
1              The request has been set up
2              The request has been sent
3              The request is in process
4              The request is complete
Now, enough theory. Let’s make a Google suggest kind of stuff and get an understanding, how AJAX works.
AJAX with ASP.NET 4.0 (.NET 4.0 framework is still in beta but a lot to offer)
We are going to use .NET 4.0 framework to show our demo of AJAX using VS.NET 2010 Express (Beta).  If you do not have VS.NET 2010 Express (Beta), you can download it fromhttp://msdn.microsoft.com/en-us/vstudio/dd582936.aspx. Remember .NET 4.0 has not been made public yet . Microsoft plans to make it public in March 2010. You can develop this demo in any serve side script you prefer.  Since I use .NET, ROR (Ruby on Rails) & PHP for my web development and since now I am playing a lot with new .NET 4.0, I planned to show the demo in VS.NET 2010 Express.  Before we start developing our Google suggest demo, I would like to make it clear that we can create AJAX based application in various way and that depends on the technology & IDE you are using. Though we will using VS.NET 2010 (Beta) for our demo, I have taken an approach which will work with all the serve side technologies with little alteration of syntaxes. Let’s design what we will be in need of:
(1)    A request page – default.aspx
(2)    A URL to call which will return the output – search.aspx
(3)    VS.NET inbuilt Sql Server 2005 support to create database file in mdf – GSuggest.mdf
(4)    A table in GSuggest.mdf – Suggestion
(5)    A column in Suggestion table – SuggestionText (nchar(100)
(6)    A LINQ to SQL file – SuggestionDB.dbml
Our pseudo code :-
(1)    Default.aspx  is our front page to communicate with web server using AJAX.
(2)    onKeyUp Javascript event of search text box on Default.aspx, calls the search.aspx page via AJAX.
(3)    Search.aspx page process the query using LINQ – SQL and returns back the output string. (Assuming only one output for our demo)
(4)    Default.aspx gets the signal from search.aspx and shows the output as we type in the characters.
Let us start building the our application.
(1) Click      Start-> Microsoft Visual Web Developer Express 2010 – ENU
pic1-1024x640
(2) Click      File-> New Project
Select “Visual C#” from Installed Templates and “ASP.NET Web Application” as application. Give you project a name (AjaxProject in our case) and choose a location to create a project.
pic2-1024x640
(3) Project will be created. Now right click  “App Data” folder -> Add  -> New Item
pic3-1024x640
(4) Select “Data” from installed templates and “Sql Server Database”. Give your database a name (GSuggest in our case).
pic4-1024x640
(5) Database created. Now go to “Database Explorer” and browse GSuggest.mdf database. Right click on it and choose “Add New Table”
pic5-1024x640
(6) Create a Column called “SuggestionText”  and data type as NCHAR(100).  Save this table as “Suggestion”.
(7) Now right click on project -> Add -> New Item.

pic71-1024x640
(8) Select “Data” as installed templates and “LINQ to SQL class” from middle. Give your dbml file name as SuggestionDB.dbml

pic8-1024x640
(9) Drag and drop the Suggestion table from database explorer to SuggestionDB.dbml file
pic9-1024x640
(10)Add following code in your Default.aspx file.

<%@ Page Title=”Home Page” Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true”
CodeBehind=”Default.aspx.cs” Inherits=”AjaxProject._Default” %>
<asp:Content ID=”HeaderContent” runat=”server” ContentPlaceHolderID=”HeadContent”>
</asp:Content>
<asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”>
<script type=”text/javascript”>
var xmlhttp = null;
function ShowSuggestions(str) {
if (str.length == 0) {
document.getElementById(”txtHint”).innerHTML = “”;
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject(”Microsoft.XMLHTTP”);
}
var url = “Search.aspx?q=” + str;
xmlhttp.open(”GET”, url, false);
xmlhttp.send(null);
document.getElementById(”txtHint”).innerHTML = xmlhttp.responseText;
}
</script>
<h2>
Welcome to ASP.NET AJAX!
</h2>
<input type=”text” id=”txt1″ onkeyup=”ShowSuggestions(this.value)” />
<p>Suggestions: <span id=”txtHint”></span></p>
</asp:Content>
Above code is very easy to understand. We are taking one input box and one txtHint span. Text box is supposed to take the input from user whereas txtHint span will render the suggestions. Please examine the input box carefully. We have used a javascript function ShowSuggestion which passes input text value id to the function. Now we already know, how to call the server using AJAX. We are taking Search.aspx page as a parameter in open method and one additional “q” parameter. Q is nothing but the parameter name for GET and we pass the input text value. As we type in this Javascript function will be called and it sends its request to search.aspx page with necessary parameter and renders the “Suggestion”.
(11)Now let’s write some code is search.aspx code behind which is suppose feed us the output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxProject
{
public partial class Search : System.Web.UI.Page
{
private SuggestionDBDataContext db = new SuggestionDBDataContext();
protected void Page_Load(object sender, EventArgs e)
{
var sugtext = db.Suggestions;
string suggestion = (from sgText in sugtext
where sgText.SuggestionText.StartsWith(Request.QueryString["q"])
select sgText.SuggestionText).FirstOrDefault();
if (string.IsNullOrEmpty(suggestion))
Response.Write(”No Suggestion Found”);
else
Response.Write(suggestion);
Response.End();
}
}
}
Let’s understand the code above. To access our table Suggestion we created a couple of minutes back, we need to connect to the database and call the Suggestion table and query if it has some data starts with the text entered in the input box (Default.aspx has sent its request). Well, Microsoft is doing enough for developers to reduce the development time. Have you realized that when we created out dbml file and dropped Suggestion table on it, it automatically creates the connection string and saved it into web.config file?  Yes, it has. So no need to explicitly define the database connection. We just have to instantiate the context created in dbml file. Since this not a tutorial on ASP.NET, so I will not explain context and other things. It may occupy a whole book if I need to write about it. You can always google around and find. The code will remain same for the developers who are working on VS.NET 2008 (.NET 3.5 framework) . Ok enough theory. Let’s understand our code we just wrote. Since we can write direct SQL code using LINQ to SQL, so we followed the same path. We just accessed the Suggestion table through sugtext and applied LIKE query (StartWith) with our input entered.
(from sgText in sugtext
where sgText.SuggestionText.StartsWith(Request.QueryString["q"])
select sgText.SuggestionText).FirstOrDefault();
Please study the above code very carefully. We just wrote a SQL query using LINQ to SQL and got our Suggestion.  Since we may or may not get the suggestion stored in the Suggestion table, so we are checking whether it is null or not.
if (string.IsNullOrEmpty(suggestion))
Response.Write(”No Suggestion Found”);
else
Response.Write(suggestion);
Response.End();
Finally we are returning back the output in our Default.aspx page using Response.Write. You may come across the below screens.
Input matches
pic10-1024x640
Input does not matches
pic11-1024x640
Yes, so simple. In fact we can trace your javascript code in VS.NET 2010 to see the entire process. Just set the breakpoints and run your application.
pic12-1024x640
Microsoft has come up with UI ToolKit called AJAX toolkit. You can navigate this linkhttp://www.codeplex.com/AjaxControlToolkit and can play with it. Using AJAXToolkit you can create a world class web application with very rich user interface.
Future of AJAX
Well, AJAX future is very promising and a lot of web applications are around for which we can feel proud. Social networks web application, corporate intranet applications, interaction with Microsoft Virtual Earth to name a few. I am sure by this time you want to go back and get your hands dirty with AJAX. So what are you waiting for? Go and make rich UI web application withAJAX and learn its true power.

Comments ( 2 )

On 10 September 2012 at 00:29 , Unknown said...

Everywhere i seen this type of topic asp.net and ajax tutorial but here you describe such a good information with good manner about ASP.Net development.

 
On 10 October 2018 at 23:29 , Tejuteju said...

it is very excellent blog and useful article thank you for sharing with us , keep posting learn more Ruby on rails Online Training India