Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Using Web API to query fetchxml in Dyanmics 365 Java Scripts

(0) ShareShare
ReportReport
Posted on by 334

I have a requirement to use Web API to query values in Dynamics 365 CRM instead of the XRMService tool kit.

The test code is below but, I keep getting an undefined error

funtcion queryxml () {

var fetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+
"  <entity name='plx_alert'>"+
"    <attribute name='plx_alertid' />"+
"    <attribute name='plx_name' />"+
"    <attribute name='createdon' />"+
"    <order attribute='plx_name' descending='false' />"+
"    <filter type='and'>"+
"      <condition attribute='plx_alertid' operator='eq' uiname='A-2334343' uitype='plx_alert' value='{7AE13339-7CEB-E711-A950-000D3AF3E215}' />"+
"    </filter>"+
"  </entity>"+
"</fetch>";
	
console.log(fetch);	
var encodedFetchXML = encodeURIComponent(fetchxml);
console.log(encodedFetchXML);
	
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/plx_alerts?fetchXml="+  encodedFetchXml, true);
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);
            var plx_name = result["plx_name"];
			console.log(plx_name);
			alert("test me  "+ plx_name);	
        } 
		
		else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();
		
}


Having used console log, I see an error saying refused to set unsafe Header content- length

fettchhhhxmllerrorrr.PNG

How can I resolve this issue.

*This post is locked for comments

  • Verified answer
    Aric Levin - MVP Profile Picture
    30,188 Moderator on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    Hi Adeyemi,

    Good job. Debugging the results is always the way to go way you get stuck on this.

    FetchXml returns multiple records, so that is correct that you need to loop through the results.

    Please go ahead and close this post (mark verified), since you have a resolution, so others can benefit from it as well.

  • Verified answer
    lawix10 Profile Picture
    334 on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    Thanks I finally figured it, I think the method returns multiple not a single value so I read another post online and I added the step.

                var returned = JSON.parse(this.responseText);
    
                var results = returned.value;
    
                for (var i = 0; i < results.length; i++)
    
                {
                    var Name = results[i]["crg_name"];		
    	        Xrm.Utility.alertDialog(Name);		
                    //TODO: Implement logic for handling results as desired
                }


    when I did not use a for loop my returned value were undefined. I dont understand it fully but debugging sure helped.

    solutionnnn.JPG

    the full code 

    function queryfetchxml()
    {
    
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+
    "  <entity name='plx_alert'>"+
    "    <attribute name='plx_alertid' />"+
    "    <attribute name='plx_name' />"+
    "    <order attribute='plx_name' descending='false' />"+
    "    <filter type='and'>"+
    "      <condition attribute='plx_alertid' operator='eq' uiname='A-00000016' uitype='plx_alert' value='{EA892529-C3F0-E711-A950-000D3AF3E215}' />"+
    "    </filter>"+
    "  </entity>"+
    "</fetch>";
    
    
    console.log(fetchXml);
    var encodedFetchXml = encodeURI(fetchXml);
    console.log(encodedFetchXml);
    
    var queryPath = "/api/data/v8.0/plx_alerts?fetchXml=" + encodedFetchXml;
    
    var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
    var req = new XMLHttpRequest();
    req.open("GET", requestPath, true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    
    req.onreadystatechange = function ()
    {
    
        if (this.readyState === 4)
    
        {
    
            this.onreadystatechange = null;
    
            if (this.status === 200)
    
            {
                var returned = JSON.parse(this.responseText);
                var results = returned.value;
                for (var i = 0; i < results.length; i++)
    
                {
                    var Name = results[i]["plx_name"];
    
    				Xrm.Utility.alertDialog(Name);
                    //TODO: Implement logic for handling results as desired
    
                }
    
            }
    
            else
    
            {
    
                alert(this.statusText);
    
            }
    
        }
    
    };
    
    req.send();
    
    
    
    
    }
  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,188 Moderator on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    The send request has to execute before it goes into the req.onreadystatechange line, so that is correct, but after the send line, it should go to back to the onreadystatechange function.

    The other thing is that it seems like you are executing the asynchronously.

    Try changing the execution to synchronous, just for testing purpose.

    In the GET line:

    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/plx_alerts?fetchXml="+  encodedFetchXml, true);

    Change the true at the end to false.

    Hope this helps.

  • lawix10 Profile Picture
    334 on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    Thanks You are right, the error mesaage is generic, I added debugger to the code, thou I havent gotten any error

    but seems the line req.onreadystatechange = function is the line where the code jumps to the last line withou executing. Thanks will try and resolve it.

    degubbbbb.PNG

  • Aric Levin - MVP Profile Picture
    30,188 Moderator on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    Are you getting any errors.

    The issue that you showed in your error message: Refused... is most likely hot related to this.

    Can you try debugging?

    F12, step by step... Put breakpoints where possible.

  • lawix10 Profile Picture
    334 on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    Thanks , that was not the issue. the equal sign was added.

  • Aric Levin - MVP Profile Picture
    30,188 Moderator on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    OK. Your screenshot was D365 CE (v9), which is what I based my reply on.

    No, you cannot use Xrm.WebApi on v8.x.

    If you are using Online as a Test Environment, you should configure it as the same version as your On-Prem environment, especially with v9, so that you code can match between the environments.

    I am not sure this is the issue, but you are missing an equal sign (=) after the fetchxml in your req.open line of code.

    Hope this helps.

  • lawix10 Profile Picture
    334 on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    the actuall version is dynamics 365 on premise, would this work, i just spinned up an online test environment..also those the method involve fetchxml?

    Regards.

  • Aric Levin - MVP Profile Picture
    30,188 Moderator on at
    RE: Using Web API to query fetchxml in Dyanmics 365 Java Scripts

    Why are you not using the OOB Web Api (Xrm.WebApi class methods), since you are on Dynamics 365 CE (v9)?

    See RetrieveMultiple function:

    docs.microsoft.com/.../retrievemultiplerecords

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Kudos to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Microsoft Dynamics CRM (Archived)

#1
Mohamed Amine Mahmoudi Profile Picture

Mohamed Amine Mahmoudi 83 Super User 2025 Season 1

#2
Community Member Profile Picture

Community Member 52

#3
Victor Onyebuchi Profile Picture

Victor Onyebuchi 6

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans