Common knowledge is that we can make JSON requests through scripts in CRM 2011 to retrieve data from CRM entities. However, the JSON request works asynchronously i.e it does not return the results immediately and the control moves to the next line of code to be executed.
It so happened during one of our development sessions is that we had to write a script to populate the values of some attributes on a form based on the value entered in another form, similar to the usual copy the phone and email once the contact is selected. We had written the JSON code for this but because it executed asynchronously the control would return to the user even before the code execution completed and the phone and email was populated on the form. The user would click on Save and Close and reported an issue that it did not bring over the phone and email…
We can replace JSON with SOAP and get this done. But we thought of getting this done by executing JSON request synchronously now that we already has the code in there to execute the call through JSON.
function retrieveRecordsSynchronously() {
var retrieveRecordsReq = new XMLHttpRequest();
var ODataPath = Xrm.Page.context.getServerUrl() + “/XRMServices/2011/OrganizationData.svc/AccountSet”;
retrieveRecordsReq.open(‘GET’, ODataPath, false);
retrieveRecordsReq.setRequestHeader(“Accept”, “application/json”);
retrieveRecordsReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
retrieveRecordsReq.send(null);
var records = JSON.parse(retrieveRecordsReq.responseText).d;
//Read the first account name
alert(‘First Account Name is: ‘ + records.results[0].Name);
}
As given in the above code we need to create the object of the XMLHttpRequest and need to open this request through ‘GET’ method. And after setting the header of this request we need to just call the send Method to send the request, after that we need to parse the response text of the request and from that we can read the results.
We are reading from AccountSet and it returns an array of accounts. Note it would only return 50 results at a time.