How to Read Dynamics 365 CRM Data in Javascript using Web API with FetchXML
In the below code snippet we can read account records whose name starts with “M” and show all names in alert.
//Retrieve Account Names whose Account Name Starts with word "M" using WEB API //Step-1 : create fetch xml in adv find and replace all double quotes with single quote inside properties to shape it as a string var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+ "<entity name='account'>"+ "<attribute name='name' />"+ "<order attribute='name' descending='false' />"+ "<filter type='and'>"+ "<condition attribute='name' operator='like' value='m%' />"+ "</filter>"+ "</entity>"+ "</fetch>"; //Step-2 : encode URI : var encodedFetchXML = encodeURI(fetchxml) var encodedFetchXML = encodeURI(fetchXml); //Step-3 : create a query path with query and odata partial uurl : var query = "/api/data/v8.0/accounts?fetchXml="+encodedFetchXML ; var query = "/api/data/v8.0/accounts?fetchXml="+encodedFetchXML; //Step-4 : create complete path : var path = Xrm.Page.context.getClientUrl() + query ; var finalpathwithquery = Xrm.Page.context.getClientUrl() + query; //Step-5 : create a XmlHttpRequest to retrieve data var data = null; var isAsync = false; var req = null; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("MSXML2.XMLHTTP.3.0"); } req.open("GET",finalpathwithquery,isAsync); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.setRequestHeader("Prefer", "odata.include-annotations=\"*\""); req.onreadystatechange = function () { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 200) { var result = JSON.parse(this.response); data = result; } else { Xrm.Utility.alertDialog(this.statusText); } } }; req.send(); //Step-6 show return result values var acclist = null; for(var i=0;i< data.value.length;i++){ acclist = acclist+" | "+data.value[i].name; } alert(acclist);