SharePoint - implement pure AJAX - Asked By Anandh Ramanujam on 08-Dec-10 04:10 AM

Hi,

I want to implement pure ajax for my page..

for example, im having one dropdownlist, after selecting an item, it will fetch the related data from the sharepoint list and bind to the few controls.

Can any body explain me in this...

Thanks.
Sreekumar P replied to Anandh Ramanujam on 08-Dec-10 04:15 AM

With the XMLHttpRequest object, Microsoft Internet Explorer clients can retrieve and submit XML data directly to a Web server without reloading the page. To convert XML data into renderable HTML content, use the client-side XML DOM or Extensible Stylesheet Language Transformations (XSLT) to compose HTML elements for presentation.

This tutorial will show you how to Working with DropDownLists by ajax  using ASP.NET 2.0 and C#.
First, you need to import the namespace from System.Data.SqlClient.

using System.Data.SqlClient;

The System.Data.SqlClient namespace contains  The System.Data.SqlClient namespace is the .NET Framework Data Provider for SQL Server.The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space.
In order to working with AJAX, we need XMLHttpRequest object. With the XMLHttpRequest object, Microsoft Internet Explorer clients can retrieve and submit XML data directly to a Web server without reloading the page. To convert XML data into renderable HTML content, use the client-side XML DOM or Extensible Stylesheet Language Transformations (XSLT) to compose HTML elements for presentation. In tutorial, we need a DropDownLists with being embed <Div> also.

The code is simple, there is nothing complex in it. In the page load event, I am register the attribute of Drowdownlist. It is for checking whether the ProvinceID is empty. If it is not be empty, I will call the function bind.

if (!Page.IsPostBack)
{
this.DropDownList1.Attributes.Add("onchange", "return startRequest();");
ListProvince();
if (ProvinceID != "")
{
GetCityByProvinceID(ProvinceID);
}
}

private DataSet GetDataSet(string sql)
{
string constring=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlDataAdapter sda =new SqlDataAdapter(sql,constring);
DataSet ds=new DataSet();
sda.Fill(ds);
return ds;
}

private void GetCityByProvinceID(string ProvinceID)
{
string connStr = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(connStr);
string sql = "select * from authors where au_id='" + ProvinceID + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();

string s = @"<table cellspacing='0' cellpadding='4' border='0' id='GridView1' style='color:#333333;border-collapse:collapse;'>";
s+="<tr style='color:White;background-color:#990000;font-weight:bold;'>";
s += "<th scope='col'>Authors_ID</th><th scope='col'>FirstName</th><th scope='col'>City</th>
<th scope='col'>Phone</th><th scope='col'>state</th><th scope='col'>zip</th></tr>";
int m = 0;
while (dr.Read())
{
if (m % 2 == 0)
{
s += "<tr style='color:#333333;background-color:#FFFBD6;'>";
}
else
{
s += "<tr style='color:#333333;background-color:White;'>";
}
m++;
s += "<td>" + dr["au_id"] + "</td>";
s += "<td>" + dr["au_fname"] + "</td>";
s += "<td>" + dr["city"] + "</td>";
s += "<td>" + dr["phone"] + "</td>";
s += "<td>" + dr["state"] + "</td>";
s += "<td>" + dr["zip"] + "</td>";
s += "</tr>";</tr>
}
s+="</table>";
dr.Close();
conn.Close();
this.Response.Write(s);
this.Response.End();
}

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

Every DropDownList is rendered as a <SELECT> element in HTML. Each of these elements has its controller, called AjaxDropDownController. The controller has a lot of things to do:

Execute asynchronous request to web server to get data.
Populate the dropdownlist.
Listen to the change event of dropdownlist.
Be the observer and the observable.
Persist the content of dropdownlist in the client side.

When the controller needs to update its dropdownlist, it will call startRequest(). While calling these methods, it may pass a filter string, which is the name-value pair of the dropdownlist that it depends to. Inside the ProvinceID value, a request URL is constructed which contains the id and filter parameters.

<script type="text/javascript">
var xmlHttp;

function createXMLHttpRequest()
{
if (window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}

function startRequest()
{
//debugger;
var ProvinceID=document.getElementById("DropDownList1");
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "?ProvinceID="+ProvinceID.value, true);
xmlHttp.send(null);
}

function handleStateChange()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
document.getElementById("gridiv").innerHTML=xmlHttp.responseText;
}
}
}
</script>

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

The front end AjaxDropDownListCsharp2005.aspx page looks something like this:

<div align="center">
<asp:Label ID="Label1" runat="server" Text="Please Slect Author's ID:"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" Width="160px">
</asp:DropDownList>
<br />
</div>

The flow for the code behind page is as follows

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

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// This tutorial is provided in part by Server Intellect Web Hosting Solutions http://www.serverintellect.com
// Visit http://www.AspNetTutorials.com for more ASP.NET Tutorials

this.DropDownList1.Attributes.Add("onchange", "return startRequest();");
ListProvince();
if (ProvinceID != "")
{
GetCityByProvinceID(ProvinceID);
}
}
}

private string ProvinceID
{
get
{
if (Request["ProvinceID"] != null && Request["ProvinceID"].ToString() != "")
{
return Request["ProvinceID"];
}
else
{
return "";
}
}
}

private DataSet GetDataSet(string sql)
{
string constring=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlDataAdapter sda =new SqlDataAdapter(sql,constring);
DataSet ds=new DataSet();
sda.Fill(ds);
return ds;
}

private void GetCityByProvinceID(string ProvinceID)
{
string connStr = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(connStr);
string sql = "select * from authors where au_id='" + ProvinceID + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();

string s = @"<table cellspacing='0' cellpadding='4' border='0' id='GridView1' style='color:#333333;border-collapse:collapse;'>";
s+="<tr style='color:White;background-color:#990000;font-weight:bold;'>";
s += "<th scope='col'>Authors_ID</th><th scope='col'>FirstName</th><th scope='col'>City</th>
<th scope='col'>Phone</th><th scope='col'>state</th><th scope='col'>zip</th></tr>";
int m = 0;
while (dr.Read())
{
if (m % 2 == 0)
{
s += "<tr style='color:#333333;background-color:#FFFBD6;'>";
}
else
{
s += "<tr style='color:#333333;background-color:White;'>";
}
m++;
s += "<td>" + dr["au_id"] + "</td>";
s += "<td>" + dr["au_fname"] + "</td>";
s += "<td>" + dr["city"] + "</td>";
s += "<td>" + dr["phone"] + "</td>";
s += "<td>" + dr["state"] + "</td>";
s += "<td>" + dr["zip"] + "</td>";
s += "</tr>";
}
s+="</table>";
dr.Close();
conn.Close();
this.Response.Write(s);
this.Response.End();
}
private void ListProvince()
{
string sql = "select * from authors";
DataSet ds = GetDataSet(sql);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "au_id";
DropDownList1.DataValueField = "au_id";
DropDownList1.DataBind();
}
}
Anandh Ramanujam replied to Sreekumar P on 08-Dec-10 04:37 AM
Thanks for your reply..

Here you have composed the HTML elements and render those to the client.

But I need to assign the values to some of the text boxes...

I have already did in code behind directly...

i.e like this..

txtOpportunityname.Text=dr["opportunity"].ToString()
txtSizeofOppoutunity.Text=dr["sizeofopportunity"].ToString()
........................
.......................
.......................

But it was not working...

Thanks.
Sreekumar P replied to Anandh Ramanujam on 08-Dec-10 09:10 AM
hi,

den u can use XML parsing for this one.

u can write a  XML data (file)  in a aspx file or in a ashx file .
here is a example with AjaxGetEmployee.ashx file


using System.Data;
using System.Web;
using System.Web.Services;
using IRmtHR;
using RmtHR;
namespace IPIXERP.HR
{
  /// <summary>
  /// Summary description for $codebehindclassname$
  /// </summary>
  ///
 
    [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class AjaxGetEmployee : IHttpHandler
  {
 
    public void ProcessRequest(HttpContext context)
    {
      //context.Response.ContentType = "text/plain";
      //context.Response.Write("Hello World");
      if (context.Request.QueryString["Id"] != null)
      {
          
          System.Text.StringBuilder sb = new System.Text.StringBuilder("<?xml version=\"1.0\"?>");
        sb.Append(@"<?xml version=""1.0"" ?>
<root>
  <data>
    <row>
      <cell>Name</cell>
      <cell>Fruit</cell>
      <cell>Vegetable</cell>
    </row>
    <row>
      <cell>Captain</cell>
      <cell>Banana</cell>
      <cell>Zucchini</cell>
    </row>
    <row>
      <cell>Admiral</cell>
      <cell>Melon</cell>
      <cell>Carrot</cell>
    </row>
    <row>
      <cell>Midshipman</cell>
      <cell>Orange</cell>
      <cell>Potatoe</cell>
    </row>
  </data>
</root>";
 
          context.Response.ContentType = "text/xml";
          System.Web.HttpContext.Current.Response.Expires = -1;
          System.Web.HttpContext.Current.Response.Write(sb.ToString());
          
      }
    }
 
    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}


<script type="text/javascript" language="javascript">
   var http_request = false;
   function makeRequest(url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
     http_request = new XMLHttpRequest();
     if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
     }
    } else if (window.ActiveXObject) { // IE
     try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
         http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
     }
    }
    if (!http_request) {
     alert('Cannot create XMLHTTP instance');
     return false;
    }
    http_request.onreadystatechange = alertContents;
    http_request.open('GET', url + parameters, true);
    http_request.send(null);
   }
 
   function alertContents() {
    if (http_request.readyState == 4) {
     if (http_request.status == 200) {
 
      var xmldoc = http_request.responseXML;
      var root = xmldoc.getElementsByTagName('root').item(0);
       
      for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
         var node = root.childNodes.item(iNode);
         for (i = 0; i < node.childNodes.length; i++) {
          var sibl = node.childNodes.item(i);
          var len = parseInt(sibl.childNodes.length / 2);
          var arr = new Array(len);
          var cnt = 0;
          for (x = 0; x < sibl.childNodes.length; x++) {
           var sibl2 = sibl.childNodes.item(x);
           var sibl3;
           if (sibl2.childNodes.length > 0) {
            sibl3 = sibl2.childNodes.item(0);
            arr[cnt] = sibl3.data;  
            cnt++;
           }
          }
          addrow("mytable", arr);
         }
      }
     } else {
      alert('There was a problem with the request.');
     }
    }
   }
   function do_xml() {
    makeRequest('AjaxGetEmployee.ashx', '?test=2');
   }
   function addrow(tablename, arr) {
   var tbl = document.getElementById(tablename);
   var lastRow = tbl.rows.length;
   var row = tbl.insertRow(lastRow);
    for (r = 0; r < arr.length; r++) {  
     var cell = row.insertCell(r);
     cell.innerHTML = arr[r];
    }
   }
 
</script>
 
<input type="button" name="button" value="GET XML"
   onclick="javascript:do_xml();">
 
<br><br>
Table filled with data requested from the server:<br>
<table border="1" id="mytable">
</table>