Tuesday, April 15, 2008

Minimizing server requests : multiple tables per request

The following example shows how to return multiple tables in one ajax request. Of course, minimizing server traffic allows for a snappy client experience. My requirement was to retrieve two data tables in a single server call. The Web service makes two distinct SQL calls, merges the datasets on the server and returns an XML document.

The client establishes a single data connection and then reads the results into two separate data stores using MemoryProxy data stores. The net effect is exactly the same result as making two (expensive) server requests.


Server Side

 [WebMethod]
public XmlDocument getPlannerDetail(String plannerid)
{
// SQL Query #1
String str = " select * from TblPlanners where plannerid = '" + plannerid + "'";
Filldt("plannerDetail", (int)Servers.nweb1, str);

DataSet localds = new DataSet();
localds.Merge(dt);

// SQL Query #2
str = "select plannerid_Owner, plannerid_Changer from TblPlanners_permission where plannerid_Owner = '" + plannerid + "'";
Filldt("Permits", (int)Servers.nweb1, str);

localds.Merge(dt);

XmlDocument doc = new XmlDocument();
xmlDoc.LoadXml(localds.GetXml());
return xmlDoc;

}

Client Side

var getdata = new Ext.data.Connection();

getdata.request({
url: "Service.asmx/getPlannerDetail",
params: {
plannerid: '123'
},
method: 'POST',
scope: this,

callback: function(options, success, response){

if (success) {
var xml = response.responseXML;

dsDetails = new Ext.data.Store({
proxy: new Ext.data.MemoryProxy(xml),
reader: new Ext.data.XmlReader({
record: 'plannerDetail',id: 'plannerid'
}, ['plannerid', 'centerid', 'LongName', 'DefaultViewRange'])
});

dsPermits = new Ext.data.Store({
proxy: new Ext.data.MemoryProxy(xml),
reader: new Ext.data.XmlReader({
record: 'Permits',
id: 'plannerid_Owner'
}, ['plannerid_Owner', 'plannerid_Changer'])
});

dsDetails.load();
dsPermits.load();
}
}
});