Execute Fetch from JavaScript in CRM 2011 by

If you are like me, you love JavaScript and use it frequently. One thing I’ve been missing is the ability to execute Fetch statements against the 2011 Organization service through JavaScript. With this basic FetchUtil JavaScript library, now you can use the 2011 service. After using this, hopefully you will find some nice little enhancements baked into the 2011 endpoint.

There are basically two files involved here. The core of it all is the FetchUtil.js which will actually build the SOAP XML and execute against CRM 2011. The second part is a small little HTML (with JavaScript embedded) showing you an example use of the FetchUtil.js file.




function FetchUtil(sOrg,sServer)
{ = sOrg;
this.server = sServer;

if (sOrg == null) {
if (typeof(ORG_UNIQUE_NAME) != “undefined”) { = ORG_UNIQUE_NAME;

if (sServer == null){
this.server = window.location.protocol + “//” +;

FetchUtil.prototype._ExecuteRequest = function(sXml, sMessage, fInternalCallback, fUserCallback)
var xmlhttp = new XMLHttpRequest();“POST”, this.server + “/XRMServices/2011/Organization.svc/web”,(fUserCallback!=null));
xmlhttp.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);
xmlhttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);
xmlhttp.setRequestHeader(“SOAPAction”, “”);

if (fUserCallback!=null)
//asynchronous: register callback function, then send the request.
var crmServiceObject = this;
xmlhttp.onreadystatechange = function(){,xmlhttp,fUserCallback) };
//synchronous: send request, then call the callback function directly

FetchUtil.prototype._HandleErrors = function(xmlhttp)
/// <summary>(private) Handles xmlhttp errors</summary>
if (xmlhttp.status != XMLHTTPSUCCESS) {
var sError = “Error: ” + xmlhttp.responseText + ” ” + xmlhttp.statusText;
return true;
} else {
return false;

FetchUtil.prototype.Fetch = function(sFetchXml, fCallback)
/// <summary>Execute a FetchXml request. (result is the response XML)</summary>
/// <param name=”sFetchXml”>fetchxml string</param>
/// <param name=”fCallback” optional=”true” type=”function”>(Optional) Async callback function if specified. If left null, function is synchronous </param>

var request = “<s:Envelope xmlns:s=””>”;
request += “<s:Body>”;

request += ‘<Execute xmlns=””>’ +
‘<request i:type=”b:RetrieveMultipleRequest” ‘ +
‘ xmlns:b=”” ‘ +
‘ xmlns:i=””>’ +
‘<b:Parameters xmlns:c=””>’ +
‘<b:KeyValuePairOfstringanyType>’ +
‘<c:key>Query</c:key>’ +
‘<c:value i:type=”b:FetchExpression”>’ +

request += CrmEncodeDecode.CrmXmlEncode(sFetchXml);

request += ‘</b:Query>’ +
‘</c:value>’ +
‘</b:KeyValuePairOfstringanyType>’ +
‘</b:Parameters>’ +
‘<b:RequestId i:nil=”true”/>’ +
‘<b:RequestName>RetrieveMultiple</b:RequestName>’ +
‘</request>’ +

request += ‘</s:Body></s:Envelope>’;

return this._ExecuteRequest(request,”Fetch”, this._FetchCallback, fCallback);

FetchUtil.prototype._FetchCallback = function(xmlhttp,callback)
///<summary>(private) Fetch message callback.</summary>
//xmlhttp must be completed
if (xmlhttp.readyState != XMLHTTPREADY)

//check for server errors
if (this._HandleErrors(xmlhttp))

var xmlReturn = xmlhttp.responseXML.xml;
xmlReturn = xmlReturn.replace(/</g, ‘&lt;’);
xmlReturn = xmlReturn.replace(/>/g, ‘&gt;’);

results = xmlReturn;

//return entity id if sync, or call user callback func if async
if (callback != null)
return results;



<title>Fetch 2011 JavaScript Example</title>
<link rel=”stylesheet” type=”text/css” href=”
/_common/styles/theme.css.aspx” />
<link rel=”stylesheet” type=”text/css” href=”
/_common/styles/global.css.aspx” />
<link rel=”stylesheet” type=”text/css” href=”
/_common/styles/fonts.css.aspx” />
<link rel=”stylesheet” type=”text/css” href=”
/_common/styles/Dialogs.css.aspx” />

<script src=”ClientGlobalContext.js.aspx”></script>
<script src=”{pub}_FetchUtil.js”></script>

<script type=”text/javascript”>

var _oService;
var _sOrgName = “”;
var _sServerUrl = GetGlobalContext().getServerUrl();

function executeFetchCommand()

var sFetch = document.getElementById(‘txtFetch’).value;
_oService = new FetchUtil(_sOrgName, _sServerUrl);
var oEntity = _oService.Fetch(sFetch, myCallBack);

function myCallBack(results){
var sOut = “”;
sOut += “<b>XML Response</b><br />”;
sOut += results;
document.getElementById(‘dvData’).innerHTML = sOut;


<table style=”width: 100%; height: 100%;” cellspacing=”0″ cellpadding=”0″ border=”0″>
<td class=”ms-crm-Dialog-Header” id=”tdDialogHeader”>
<div id=”divTitle” class=”ms-crm-Dialog-Header-Title”>Executing Fetch from JavaScript in CRM 2011</div>
<div id=”divInstructions” class=”ms-crm-Dialog-Header-Desc”>Enter some FetchXML to be executed against your CRM environment</div>
<td style=”height: 100%;”>
<div class=”ms-crm-Dialog-Main” style=”padding: 14px;”>
<label>Fetch Command</label><br />
<textarea id=”txtFetch” rows=”8″ width=”100%” cols=”100″ ></textarea><br />
<input type=”Submit” value=”Fetch” onClick=”javascript:executeFetchCommand();” style=”width:100px;height:24px;”>
<div id=’dvData’ style=”width: 100%; height: 100%;”></div>
<td class=”ms-crm-Dialog-Footer” id=”tdDialogFooter”>
<table cellspacing=”0″ cellpadding=”0″>
<td width=”100%”></td>
<td>&nbsp;<button onclick=”window.close();” class=”ms-crm-Button”>Done</button></td>



Now that we have our JavaScript utility and our Fetch example, we need to do a few things.

  1. We need a solution to put these two files into (feel free to add it to an existing solution or create one named whatever you like).
  2. Let’s now import the FetchUtil.js file and publish. Take note of the Publisher Prefix (the letters in front of the name).
  3. We now need to modify the fetchExample.htm file to point to this FetchUtil.js by replacing the {pub} with your Publisher Prefix (ex. “new_FetchUtil.js”).
  4. We also need to modify the _sServerUrl and change the {org} to the appropriate organization abbreviation. If you are using the onsite, you will need to change the entire URL to match accordingly.
  5. Finally, let’s upload the fetchExample.htm file and publish.


This should now bring you to a super fancy screen to paste some Fetch into.



Well there you have it. The next step is to parse the XML with jQuery, RegEx, traversing the nodes, or however you prefer. Hope you enjoy!

On-Premises vs. Cloud CRM

A guide to help you determine the best solutions for you.

Download for Free