Tuesday, December 29, 2009

Execute Method using Java Script

Hi,
Here is an example to execute request only in Client Side

// Prepare variables to add a new product to a campaign.
var CampaignId = "771ed82b-6b27-dd11-b452-0003ff9ee217";
var EntityId = "3F26C82A-A2E1-DC11-A277-001AA0B84538";
var EntityName = "product";
var authenticationHeader = GenerateAuthenticationHeader();

// Prepare the SOAP message.
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'>"+
authenticationHeader+
"<soap:Body>"+
"<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<Request xsi:type='AddItemCampaignRequest'>"+
"<CampaignId>"+CampaignId+"</CampaignId>"+
"<EntityId>"+EntityId+"</EntityId>"+
"<EntityName>"+EntityName+"</EntityName>"+
"</Request>"+
"</Execute>"+
"</soap:Body>"+
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;

// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
// Display a confirmation message and open the campaign record.
else
{
alert("Product with id = "+EntityId+" successfully added to Campaign with id = "+CampaignId+".");
window.open("/ma/camps/edit.aspx?id={"+CampaignId+"}");
}


Enjoy,
Rami Heleg