8

Getting data from a list using rest API.
Here is my code ,

function getItems(url) {    
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            console.log(data.d.results);
            return data.d.results;
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}


Here is the function call,

var result = getItems("/_api/Web/Lists/GetByTitle('LISTNAME')/Items?$select=ID,FIELD1,FIELD2,FIELD3");


I am getting the items in console. But when trying to access 'result' variable it showing undefined. how can I return the result data. can i solve it by callback, promise or any other way...

14

You have to learn all about the async nature of REST calls.

It is like when you order someone to get you a coffee:

the request is Asynchronous; you do not get an immediate response

Your function getItems can not have a return value, as the Ajax request is still fetching your coffee.
That is why your getItems Function returns undefined

And your return in the success callback is not the return for getItems,
that return value goes nowhere, Callbacks can not return values

You have to learn the difference between (oldskool) CallBacks and (more powerfull) Promises
(Note: in future JavaScript versions you will learn to use Generators/Async/Await)

If you go with the Promises pattern you will do something like:

function getItems(url) {    
    return $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
}

getItems( "/_api/Web/Lists/GetByTitle('Tasks')/Items" ).done(function(data){
     data.d.results.forEach(function(item){  // no need for oldskool for loops
        console.log( item.ID, item.Title );
     });
});

also read: REST call to get list not working

iREST

  • thanks for the Info. How to add return in my getItems function correctly? – Vishnu S May 15 '17 at 11:50
  • 4
    You can not because the call is asynchronous, the above code shows how to return a Promise and then continue (.done) with the data when the Promise is resolved, see the last link for more code – Danny '365CSI' Engelman May 15 '17 at 11:51
  • This one is really a great example and good practice.. – Trimantra Software Solution May 16 '17 at 5:28
6

There is one more way to implement. Please refer below code:

var url = "/_api/Web/Lists/GetByTitle('LISTNAME')/Items?$select=ID,FIELD1,FIELD2,FIELD3";

getItems(url).then(getItemsSuccess, getItemsFail);

function getItems(url){
    return $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
}

function getItemsSuccess(data){
    if(data.d.results.length > 0){
        console.log(data.d.results);
        var result = data.d.results; // set value of result variable 
    }
}

function getItemsFail(err){
    // error callback
}
  • 1
    this one also works... – Vishnu S May 15 '17 at 11:43
5

Try in this way:

function getItems(url,success) {    
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            console.log(data.d.results);
            success(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

and then just call the function like:

getItems('YOUR URL',function(data){
var result = data;
// Use 'result' variable
});

Callback function always works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.