Pages

Wednesday, 17 April 2013

JQuery asynchronous and synchronous retrieve using REST in CRM 2011

In this article , i am going to explain how to make asynchronous and synchronous call using javascript in CRM 2011

first you need to add JQuery file on form as webresource and if you want to run javascript code asynchronous  then make async attribute value true else false in below code


function Retrieve() {
    var jSonArray = new Array();

    if (Xrm.Page.getAttribute("account").getValue() != null) {
        //acount guid no
        var studentid = Xrm.Page.data.entity.attributes.get("account").getValue()[0].id;

        var filter = "$select=name&$filter=accountid eq guid'" + studentid + "'"
        var entityset = 'account';

        var pagecontext = Xrm.Page.context;
        var serverUrl = pagecontext.getServerUrl();
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        var odataSelect = serverUrl + "/xrmservices/2011/OrganizationData.svc/" + entityset + "Set?" + filter;

        //asynchronous call -> async: true
        //synchronous call -> async: true
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                jSonArray.push(data.d);
                onSaveSuccess(jSonArray);
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
        });
    }

}

function onSaveSuccess(jSonArray) {
    if (jSonArray != null && jSonArray[0].results.length > 0) {
        var accountname = jSonArray[0].results[0].name;
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.