Monday, April 22, 2013

Retrieving more than 50 record using REST OData in JavaScript


Normally we can retrieve only 50 records using an OData Rest End Points method for a single fetch.  Since the retrieve method also returns the paging cookie, we can iterate the retrieve process until we retrieve all records.  But while retrieving large number of data the performance will be significantly affected.
Below is the code to iterate the retrieve process until all records are retrieved.
var oReturn = null;
function RetrieveData() {
    var context = GetGlobalContext();
    var serverUrl = context.getServerUrl();
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc/EntitySet";
    jQuery.support.cors = true;
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataPath,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data.d != null) {
                    var odataReturn = data.d;
                    if (oReturn == null)
                        oReturn = odataReturn.results;
                    else
                        oReturn = oReturn.concat(odataReturn.results);

     //Check if more records available in the page and call the same RetrieveData()

                    if (null != odataReturn._next) {
                        _next = odataReturn._next;
                        RetrieveData();
                    }
                }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) { alert('Unable to retrieve data:' + textStatus); }
    });
    return oReturn;

Hope this is helpful;

No comments:

Post a Comment