Click here to Skip to main content
15,891,864 members
Articles / Web Development / ASP.NET

Simply AJAX

Rate me:
Please Sign up or sign in to vote.
3.11/5 (15 votes)
9 Jul 2007CPOL2 min read 46.4K   387   26  
This article illustrates how to implement a simple AJAX example
<%@ Page language="c#" validateRequest="false" Inherits="AjaxStoredProc.WebForm1" CodeFile="Passer.aspx.cs" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>WebForm1</title>
		<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
		<meta name="CODE_LANGUAGE" Content="C#">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
		<script>
		
		
	var http_request=false;
		function Begin()
	{
	
	 //////////////////////  Create ActiveX Object (Microsoft) /////////////////
       try 
       {
        http_request = new XMLHttpRequest();
       }
         catch (e)
         {
           try 
           {
            http_request = new ActiveXObject("MsXML_Container.XMLHTTP");
           } 
            catch (o)
            {
               try
               {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
               }
                catch (failed)
                {
                 http_request = false;
                }
            }//End catch (e)
        }//End catch(o)

      if (!http_request)
      alert("Error initializing XMLHttpRequest!");
     ///////////////////////////////////////////////////////////////////////

	//// URL //// This is the page that processes the request and then returns the XML
	// Append ?(selection) to the url (dropdownlist value in this example)
    var url="Catch.aspx?choice=" + document.forms[0].ddlChoice.value;
    /// Open Params Send /////////////
    http_request.open("GET",url,true);
    http_request.setRequestHeader('content-type', 'text/xml');
    http_request.setRequestHeader('Cache-Control:', 'no-cache');
    // Define the Javascript function to handle the response/////////////////////////
    http_request.onreadystatechange = ShowResults;                                 //
    http_request.send(null);// Send the request to Catch.aspx                      //
	}// End Begin                                                                  //
	                                                                               //
	function ShowResults()//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//
	{
	  var Request_Text=""; // Variable to hold the XML/Text returned from Catch.aspx
	  if (http_request.readyState == 4)
	  if (http_request.status==200)// Make sure the response is valid and Complete
	     {
	       Request_Text=http_request.responseText;// Assign the response
	      
           var XML_Container = new ActiveXObject("Microsoft.XMLDOM");// Create XML Container
           XML_Container.async = false;
           XML_Container.loadXML(Request_Text);// Load the Container with the Text Response
           
           ////////////////////////////////////////////////////////////////////////////////
          // At this point, you have successfully requested the information and it has been
          // returned to you in text format (request.responseText) and have loaded it into
          // an XML container (XML_Container). Now the parsing and the populating of your
          // desired control can begin. (A dynamically generated table in this case.)/////
          ///////////////////////////////////////////////////////////////////////////////
          
          // Remove table if not the first response////////////
           try
           {
           document.getElementById("MyTable").removeNode(true);
           }
           catch(e){}
           ////////////////////////////////////////////////////
           
      
          // Navigate through the XML and Assign Tags to Variables(arrays) //
          
          var Choice = XML_Container.getElementsByTagName("Choice");
          var Comment  = XML_Container.getElementsByTagName("Comment");
          var Comment1  = XML_Container.getElementsByTagName("Comment1");
          var Comment2 = XML_Container.getElementsByTagName("Comment2");
          var Comment3  = XML_Container.getElementsByTagName("Comment3");
          
          // Create the table to hold the data//
          CreateTable(5,1);
          
          // Iterate through the HTML table and insert data into cells//
          // Note: The following loads an HTML table, you can populate
          // whatever control you need to.
          
          var myTable = document.getElementById("MyTable");
          var TableRows = myTable.getElementsByTagName("tr");// Rows
          var TableColumns = null;
             var cell = null;
             var cell1 = null;
             var cell2 = null;
             var cell3 = null;
             var cell4 = null;
       
     
	        var strChoice    =  Choice[0].firstChild.nodeValue;
	        var strComment   =  Comment[0].firstChild.nodeValue;
	        var strComment1  =  Comment1[0].firstChild.nodeValue;
	        var strComment2  =  Comment2[0].firstChild.nodeValue;
	        var strComment3  =  Comment3[0].firstChild.nodeValue;
	        
	       ///////////////////////////////////////////////////
          
		            TableColumns = TableRows[0].getElementsByTagName("td");// Cells
                     
                      cell = TableColumns[0].getElementsByTagName("input") ;
                      cell[0].value=strChoice; 
                      cell1 = TableColumns[1].getElementsByTagName("input") ;
                      cell1[0].value=strComment;
                      cell2 = TableColumns[2].getElementsByTagName("input") ;
                      cell2[0].value=strComment1;
                      cell3 = TableColumns[3].getElementsByTagName("input") ;
                      cell3[0].value=strComment2;
                      cell4 = TableColumns[4].getElementsByTagName("input") ;
                      cell4[0].value=strComment3;
                  
	    }//End If
	}//End Show Results
	
	

		</script>
	</HEAD>
	
	<script>
	function CreateTable(c,r)
	{
	var body = document.getElementsByTagName("body")[0];

        var newTable     = document.createElement("Table");
        newTable.id="MyTable";
        var newTableBody = document.createElement("tbody");

        // r = rows
        for (var j = 0; j < r; j++) {
            var row = document.createElement("tr");
        // c = columns
            for (var i = 0; i < c; i++) 
            {
                var cell = document.createElement("td");
                var newElm = document.createElement('input');
                cell.appendChild(newElm);
                row.appendChild(cell);
            }

            newTableBody.appendChild(row);
        }
        newTable.appendChild(newTableBody);
        body.appendChild(newTable);
        newTable.setAttribute("border", "1");
	}
	</script>
	
	<body>
		<form id="Form1" method="post" runat="server">
			<asp:TextBox id="TextBox2" style="Z-INDEX: 100; LEFT: 504px; POSITION: absolute; TOP: 64px" runat="server"
				Height="0px" Width="0px" TextMode="MultiLine"></asp:TextBox>
			<asp:DropDownList id="ddlChoice" style="Z-INDEX: 101; LEFT: 266px; POSITION: absolute; TOP: 105px"
				runat="server" Width="128px"></asp:DropDownList>
			<asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 976px; POSITION: absolute; TOP: 72px" runat="server"
				Text="Button" Width="0px"></asp:Button>
            &nbsp;&nbsp;&nbsp;
            
		</form>
	</body>
</HTML>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions