Search This Blog

Friday, November 28, 2014

using OData in Javascript MS CRM 2013


Here is code  for how to fetch entity records from JavaScript Using OData
use Schema names for field names

function MainFunction()
{
    var project = getLookupId("ap_project");
    if (project != null) {
        var filter = "&$filter=";
        filter += "ap_projectId eq guid'" + project + "'";
        var odataQuery = "/ap_projectSet?$select=ap_projectId,ap_TypeOfContract" + filter;
        ExecuteQuery(odataQuery, true, function (data) {
            if (data && data.d && data.d.results && data.d.results[0])
           {
               // Get Results here
                       var typeofcontract = data.d.results[0].yourfieldname.Value;
              
            }
        });
    }
}

function ExecuteQuery(odataQuery, sync, callback) {
    var async = true;
    if (sync) {
        async = false;
    }
    var odataPath = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc";
    var odataUrl = odataPath + odataQuery;
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataUrl,
        async: async,
        beforeSend: function (xmlHttpRequest) {
            xmlHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, xmlHttpRequest) {
            if (callback) {
                callback(data);
            }
        },
        error: function (xmlHttpRequest, textStatus, errorObject) {
            alert("Error Occurred : " + textStatus + ": " + JSON.parse(xmlHttpRequest.responseText).error.message.value);
        }
    });
}

function getLookupId(lookupName) {
    var lookupItem = new Array();
    lookupItem = Xrm.Page.getAttribute(lookupName).getValue();
    if (lookupItem != null) {
        return lookupItem[0].id;
    }
    else
        return null;
}

No comments:

Post a Comment