Monday, August 31, 2009

AJAX Calls using JavaScript to retrieve data for N:N relationship in MS CRM 4.0

//**************************************************
//AJAX Call to get the Competitors for an Oportunity
//**************************************************


var sOppID = crmForm.ObjectId;

var returnXML="";

var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>competitor</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:AllColumns\" />" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>competitorid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>competitor</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>opportunitycompetitors</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>competitorid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>opportunityid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>opportunitycompetitors</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>opportunity</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>opportunityid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkCriteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>opportunityid</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">" + sOppID + "</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:LinkCriteria>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var returnXML = xmlHttpRequest.responseXML;

if(returnXML != null)
{
var returnNodes = returnXML.selectNodes("//BusinessEntity/q1:competitorid");
if(returnNodes.length > 0)
{

// DEFINE YOUR LOGIC HERE


}
}

No comments: