Search code examples
javascriptrestsharepoint-2010

SharePoint 2010 Rest API error (Not retrieving data)


When I run the code below, I get the following error: "Unable to get property 'results' of undefined or null reference"

$(document).ready(function() { 
var iceCreamApp = {};
iceCreamApp.Truck = new Array();

//Load data from list into array right away
(function() {
    var url = "http://isaac.issharepoint.com/demo/_api/web/lists/GetByTitle('IceCreamTrucks')/items?$select=State";
    $.ajax({
        url:url,
        type:"GET",
        dataType:"json",
        headers: {"Accept": "application/json; odata=verbose"},
        success: function(data) {
            success(data);
        },
        error: function(data) {
            //failure(data);
        }
    })

        function success(data)
        {
            console.log(data);
        }
}());


})

Solution

  • This error occurs since in success callback you've already getting results object:

    success(data.d)  //<-- data.d returns results object
    

    So, the solution would be to replace the line

    function success(data)
    {
        console.log(data.d.results);
    }
    

    with this one:

    function success(results)
    {
         console.log(results);
    }
    

    You could also consider to utilize some library when working with SharePoint 2010 RESTful API. The following example demonstrates how get list items using datajs JavaScript library:

    OData.read({ 
        requestUri: _spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/IceCreamTrucks?$select=State", 
        enableJsonpCallback: true
       }, 
       function (data) {
           for(var i =0; i < data.results.length; i++) {
               console.log(data.results[i].State);  
           } 
       }, 
       function (err) {
          // error function.
    });