Home > CRM 2011, JScript > Retrieve record using OData and JQuery in CRM 2011

Retrieve record using OData and JQuery in CRM 2011

Hi,

Below is the script to read a record using OData & JQuery

function retrieveRecord(id, odataSetName) {

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

//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 + “/” + odataSetName + “(guid'” + id + “‘)”,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

},

success: function (data, textStatus, XmlHttpRequest) {

readRecord(data, textStatus, XmlHttpRequest)

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert(“Error – ” + errorThrown)

}

});

}

function readRecord(data, textStatus, XmlHttpRequest) {

alert(“Record read successfully!!”);

var account = data;

alert(“Name – ” + account.d.Name);

alert(“Id – ” + account.d.AccountId);

}

How do I call this method :-

  • Below is the sample function to read Account

var accountId = “”; // Assign account GUID

var odataSetName = “AccountSet”;

retrieveRecord(accountId,odataSetName );

Hope it helps 🙂

Advertisement
  1. Jaques Els
    February 17, 2012 at 7:18 PM

    The code works, but does not actually read the record, it goes into

    function readRecord(data, textStatus, XmlHttpRequest) {
    alert(“Record read successfully!”);
    var account = data;
    alert(“Name – ” + account.Name);
    alert(“Id – ” + account.AccountId);
    }
    But then account.Name and account.AccountId is NULL?

    Is there anything I am doing wrong?

  2. Jaques Els
    February 17, 2012 at 9:04 PM

    It needed the data.d.Name to work…

    function readRecord(data, textStatus, XmlHttpRequest) {

    var aName = “”;
    var aID = “”;

    var account = data;
    if (account.Name != null)
    aName = account.Name;
    else
    aName = data.d.Name;

    if (account.AccountId!= null)
    aID = account.AccountId;
    else
    aID = data.d.AccountId;
    }

  3. February 23, 2012 at 7:35 PM

    function retrieveRecord(id, odataSetName, successCallback, errorCallback) {

    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

    alert(serverUrl);
    alert(ODATA_ENDPOINT);
    alert(id);
    alert(odataSetName);

    if (!id) {
    alert(“record id is required.”);
    return;
    }

    if (!odataSetName) {
    alert(“odataSetName is required.”);
    return;
    }

    $.ajax({
    type: “GET”,
    contentType: “application/json; charset=utf-8”,
    datatype: “json”,
    url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)”,
    beforeSend: function (XMLHttpRequest) {
    //Specifying this header ensures that the results will be returned as JSON.
    XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
    },
    success: function (data, textStatus, XmlHttpRequest) {
    if (successCallback) {
    successCallback(data.d, textStatus, XmlHttpRequest);
    }
    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
    if (errorCallback)
    errorCallback(XmlHttpRequest, textStatus, errorThrown);
    else
    errorHandler(XmlHttpRequest, textStatus, errorThrown);
    }
    });
    }

    function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
    alert(“Error : ” + textStatus + “: ” + xmlHttpRequest.statusText);
    }

    function retrieveAccount(id) {

    //alert(“ACTION: Retrieving Account with id: ” + id.toString());

    retrieveRecord(id, “AccountSet”, retrieveAccountCompleted, null);
    }

    function retrieveAccountCompleted(data, textStatus, XmlHttpRequest) {

    //Get back the Account JSON object
    //var account = data;
    //alert(“Account retrieved: account name = \”” + account.Name + “\”, id = {” + account.AccountId + “}”);

    //NEXT STEP: Update the Account
    //updateAccount(account.AccountId);
    }

    function getLocation()
    {

    var lookupObject = Xrm.Page.getAttribute(“regardingobjectid”);

    if (lookupObject != null)
    {

    var lookUpObjectValue = lookupObject.getValue();

    if ((lookUpObjectValue != null))
    {

    var doctorlookuptextvalue = lookUpObjectValue[0].name;

    var doctorlookupid = lookUpObjectValue[0].id;

    }

    }

    retrieveAccount(doctorlookupid);
    }

    I am getting a error that $ is undefined . Can you suggest me what is the wrong here ?

    • Jaques Els
      February 23, 2012 at 9:41 PM

      you need to copy json2.js and jquery-1.4.1.js into the web resources and add to your Form Libraries.

      • February 25, 2012 at 10:39 AM

        Hi Jaques, I have a issue and hope you or someone else can help me with that.

        Last month I created a webresource to retrieve data using oData endpoint filter, added json2.js and jquery-1.4.1.min.js. It was working fine.

        uri was : http://…../AccountSet?$filter= address1_city eq Jaipur

        Yesterday I tried oData endpoint to retrieve account by id:
        http://…../Account(Guid’xxxxxxxx’)
        also added json2.js and jquery-1.4.1.min.js., but this time I get undefined in result for data.d.fieldname.

        Then I tried json2.js and jquery-1.4.1.js, and this time my code was working fine.

        So can you please tell me what is the difference between jquery-1.4.1.min.js and jquery-1.4.1.js, and why jquery-1.4.1.min.js is not working when I am retrieving single record.

        Thanks in advance.

  4. February 25, 2012 at 10:47 AM

    nmathur :
    Hi Jaques, I have a issue and hope you or someone else can help me with that.
    Last month I created a webresource to retrieve data using oData endpoint filter, added json2.js and jquery-1.4.1.min.js. It was working fine.
    uri was : http://…../AccountSet?$filter= address1_city eq Jaipur
    Yesterday I tried oData endpoint to retrieve account by id:
    http://…../Account(Guid’xxxxxxxx’)
    also added json2.js and jquery-1.4.1.min.js., but this time I get undefined in result for data.d.fieldname.
    Then I tried json2.js, jquery-1.4.1.min.js and jquery-1.4.1.js, and this time my code was working fine.
    So can you please tell me what is the difference between jquery-1.4.1.min.js and jquery-1.4.1.js, and why jquery-1.4.1.min.js and json2.js are not working when I am retrieving single record.
    Thanks in advance.

  5. February 25, 2012 at 10:50 AM

    nmathur :
    sorry forgot to mention, jquery.1.4.1.min.js was also there with json2.js and jquery.1.4.1.js

  6. February 25, 2012 at 9:26 PM

    Hello All,

    I have the below query where I read a custom field location from the parent form (Contact) using JQuery . I am trying to get the parent customer id of contact also using the same way . However I am not able to get it . In the alert I get a object . But dont know how to get the id , name or entitytypename of the object .

    Could you help me ?

    function retrieveContactReqCallBack(retrieveContactReq) {
    if (retrieveContactReq.readyState == 4 /* complete */) {
    if (retrieveContactReq.status == 200) {
    //Success

    var retrievedContact = JSON.parse(retrieveContactReq.responseText).d;

    alert(retrievedContact.ParentCustomerId);
    Xrm.Page.getAttribute(“location”).setValue(retrievedContact.insyweb_Location);

    Xrm.Page.getAttribute(“insyweb_Location”).setValue(retrievedContact.ParentCustomerId);

    }
    else {
    //Failure
    errorHandler(retrieveContactReq);
    alert(“retrieveContactReqCallBack function failure END”);
    }
    }
    }

    Thanks,
    Prasun

  7. February 26, 2012 at 4:38 PM

    Hi Prasun,
    Please try this
    function retrieveReqCallBack(retrieveReq) {
    if (retrieveReq.readyState == 4 /* complete */) {
    var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
    var EmailAddress = retrieved.results[0].EMailAddress1;
    alert(EmailAddress);
    }
    }

    ** Make sure field names are same as scehema names.
    Tip :- If you have Query Designer read the names from that

    • Jaques
      March 7, 2012 at 3:53 PM

      I am trying to Qualify/Disqualfy (Set State in Lead using Java Script) I am not successful… can you please help

      var requestMain = “”
      requestMain += “”;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ”
      “;
      requestMain += ” EntityMoniker”;
      requestMain += ” “;
      requestMain += ”
      ” + target + ““;
      requestMain += ” ” + entityName + ““;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ”
      “;
      requestMain += ” “;
      requestMain += ” State”;
      requestMain += ” “;
      // requestMain += ”
      1“;
      requestMain += ” ” + stateValue + ““;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” Status”;
      requestMain += ” “;
      requestMain += ”
      ” + statusCodeValue + ““;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ”
      SetState“;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += ” “;
      requestMain += “”;

      var serverUrl = _getServerUrl();
      var req = new XMLHttpRequest();
      req.open(“POST”, serverUrl, false)
      // Responses will return XML. It isn’t possible to return JSON.
      req.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);
      req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);
      req.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute”);
      var successCallback = null;
      var errorCallback = null;
      req.onreadystatechange = function () {
      setStateResponse(req);
      //SetStateResponse(req, successCallback, errorCallback);
      };
      req.send(requestMain);

      }

      function setStateResponse(req) {

      //Xrm.Page.data.entity.save();
      //Xrm.Page.data.entity.save(“SaveAndClose”);

      debugger;
      var id = Xrm.Page.data.entity.getId();

      if (req.readyState == 4) {
      if (req.status == 200) {
      //Xrm.Page.data.entity.save(“SaveAndClose”);
      alert(“Success !!!”);
      }
      else {
      //alert(“Error – ” + req.responseXML);
      }
      }
      }

      // This function gets called after the execution
      function SetStateResponse(req, successCallback, errorCallback) {
      debugger;
      if (req.readyState == 4) {
      if (req.status == 200) {
      if (successCallback != null)
      { successCallback(); }
      }
      else {
      errorCallback(_getError(req.responseXML));
      }
      }
      }

      function _getError(faultXml) {
      var errorMessage = “Unknown Error (Unable to parse the fault)”;
      if (typeof faultXml == “object”) {
      try {
      var bodyNode = faultXml.firstChild.firstChild;
      //Retrieve the fault node
      for (var i = 0; i < bodyNode.childNodes.length; i++) {
      var node = bodyNode.childNodes[i];
      //NOTE: This comparison does not handle the case where the XML namespace changes
      if ("s:Fault" == node.nodeName) {
      for (var j = 0; j < node.childNodes.length; j++) {
      var faultStringNode = node.childNodes[j];
      if ("faultstring" == faultStringNode.nodeName) {
      errorMessage = faultStringNode.text;
      break;
      }
      }
      break;
      }
      }
      }
      catch (e) { };
      }
      return new Error(errorMessage);
      }

  1. No trackbacks yet.

Leave a Reply to Jaques Els Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: