Saturday, March 17, 2012

Ajax in

Ajax Overview:-

·         AJAX = Asynchronous JavaScript and XML.
·         AJAX is not a new programming language, but a new way to use existing standards.
·         AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
·         AJAX is a technique for creating fast and dynamic web pages.
·         AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
·         Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Now let us see how this ajax is sending the request to the server and getting the response from the server
AJAX is based on internet standards, and uses a combination of:
  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)
The XMLHttpRequest Object
·         All modern browsers support the XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).
·         The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
·         All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
·         Syntax for creating an XMLHttpRequest object:
xmlhttp=new XMLHttpRequest();
·         Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:"GET","ajax_info.txt",true);

Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
Sends the request off to the server.

string: Only used for POST requests

The responseText Property
If the response from the server is not XML, use the responseText property.
The responseText property returns the response as a string, and you can use it accordingly:
The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:

Stores a function (or the name of a function) to be called automatically each time the readyState property changes
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
200: "OK"
404: Page not found
In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.
When readyState is 4 and status is 200, the response is ready.
Now we got an idea what is ajax and how to get the data using ajax.  Now we will see how this ajax can be used in our Let us see with an example.
1.      Create a New Website.  default.aspx page will be opened as default.
2.      Add a Jscript i.e., Java script file to our project.
3.      Add the following code to it.

    function GetXmlHttpObject(handler)
          var objXmlHttp = null
          if (navigator.userAgent.indexOf("Opera") >= 0)
              alert("This example doesn't work in Opera")
          if (navigator.userAgent.indexOf("MSIE") >= 0)
              var strName = "Msxml2.XMLHTTP"
              if (navigator.appVersion.indexOf("MSIE 5.5") >= 0)
                  strName = "Microsoft.XMLHTTP"
                  objXmlHttp = new ActiveXObject(strName)
                  objXmlHttp.onreadystatechange = handler
                  return objXmlHttp
              catch (e)
                  alert("Error. Scripting for ActiveX might be disabled")
          if (navigator.userAgent.indexOf("Mozilla") >= 0)
              objXmlHttp = new XMLHttpRequest()
              objXmlHttp.onload = handler
              objXmlHttp.onerror = handler
              return objXmlHttp

4.      The above method creates and returns the xmlhttpobject by assigning an event handler to the object.
5.      Add the following method to the above js file.
    function stateChanged()
          if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
            document.getElementById("data").innerHTML=             xmlHttp.responseText;


6.      The above (stateChanged()) method is the handler which invokes when the response from the server is obtained.
7.      Add the following method to the same js file.
    function GetData()
          var url = "default.aspx?qstring=1";
          xmlHttp = GetXmlHttpObject(stateChanged);
"GET", url, true);
8.      This is the main function which we can call it at any event or any time according to our requirement.  Here we are passing the Query String to the default.aspx page and by using that string the whole manipulation will done at backend.
9.      Now add this js file to the page in the head part.
10.  Now we have completed the Ajax coding. Only the thing we have to do is, writing the backend coding for getting the data from the database.
11.  Now open the code file and do the following changes to the code in the  pageload event:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (Request.QueryString["qstring"] != null)
            SqlConnection con = new SqlConnection("");
            string select = "select * from Data_Capture_Personal_Det";
            SqlCommand cmd = new SqlCommand(select, con);
            SqlDataReader dr = cmd.ExecuteReader();
            StringBuilder sb = new StringBuilder();
            while (dr.Read())
First Name :" + dr[4].ToString() + "
Last Name :" + dr[5].ToString() + "
Middle Name :" + dr[6].ToString() + "


12.  Now above is your code page and below is your aspx page.

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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <title>Untitled Pagetitle>
    <script src="JScript.js" type="text/javascript">script>
    <form id="form1" runat="server">
    <input type="button" value="GetData" onclick="GetData();" />
    <div id="data">

13.  Now run project by pressing F5 and click the button. The data will be displayed in the table format without a postback.
14.  See here we are seperating the functions accroding the the querystring which we pass for the respective data in the codebehind. .i.e., we are getting the data by using the querystring.
Note: The query string will not be visible in the addressbar.