How To – Series 8: Cross Domain Issue while working with CRM 2011 Web Services in JScript

Back to blogging after long time. Recently I faced a “Cross Domain” issue while working with Jscript ODATA query. Below is the code which I have used:
    var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
    var context = GetGlobalContext();
    var serverUrl = context.getServerUrl();
   
    //Asynchronous AJAX function to Retrieve a CRM record using OData
    $.ajax({
        type: “GET”,
        contentType: “application/json; charset=utf-8”,
        datatype: “json”,
        url: serverUrl + ODATA_ENDPOINT + “/AccountSet?$filter=Address1_City eq ‘Redmond'”,
        beforeSend: function (XMLHttpRequest)
        {
            XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
        },
        success: function (data, textStatus, XmlHttpRequest)
        {
              // Success Call Back
        },
        error: function (XmlHttpRequest, textStatus, errorThrown)
        {
              // Error Call Back
        }
    });
The REST End point “url “ which I am passing in the above code is: http://<server>/<orgname>/XRMServices/2011/OrganizationData.svc/AccountSet?$filter=Address1_City eq ‘Redmond’.This code only works when we open CRM records using CRM “Server” name. It fails in other cases like when we open it using IP Address or localhost. The primary reason for this is due to “Cross Domain Policy”. The blocker is the REST End point which we are using. 
So, I thought of replacing server name with IP Address as follows.
I ran it in the browser…. It worked…!!!! J
So, I got a simple solution. 
Use the following instead of getting “ServerUrl” from the context object.
    var serverUrl = window.location.protocol + “//” + window.location.host + “/” + context.getOrgUniqueName();
Here we just need to use the window.location property to get the current window protocol and host and build the REST Endpoint.
Hope it helps…!!!! Please let me know if we have any other alternative solution. 
Cheers
Vikranth Pandiri.

One thought on “How To – Series 8: Cross Domain Issue while working with CRM 2011 Web Services in JScript

Comments are closed.