0

I'm learning SP and how to perform operations via REST. I am unable to access the data returned by my REST call outside of the ajax call. Essentially, I want to make a REST call to get data and then use that data elsewhere in my script. I've googled but can't find an answer that I've been able to implement. Below is my REST call. The console.log inside the success function returns my data as expected...but how can I access my data outside of this? I tried many solutions that seem to maybe fit but nothing is of help. I've tried saving getListData() as a variable and then console logging that variable to see if anything is returned but that is not working. Any help is appreciated!

function getListData(listName){
        $.ajax({
        url: _spPageContextInfo.siteServerRelativeUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
            method: 'GET',
            beforeSend: function (XMLHttpRequest){
                XMLHttpRequest.setRequestHeader('Accept', 'application/json; odata=verbose');
                },
            success: function( data ) {
                console.log(data.d.results);
                success(data.d.results);                
            }

        }); 
    }
1

They are multiple ways to do it, below 2 are some of the simplest ways to get data after your ajax request succeeds.

Option 1 - call another js function after your ajax request succeeds somewhat as below:

function getListData(listName){
    $.ajax({
        url: _spPageContextInfo.siteServerRelativeUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
        success: function( data ) {
            console.log(data.d.results);
            renderDataToHtml(data.d.results);
        },
        error:function(data){
            console.log("something went wrong");
        }
    }); 
}

function renderDataToHtml(data){
    data.forEach(function(item){ 
        console.log(item.Title);
    });
}

Option 2 - implement promises. Much more cleaner and legible.

function getListData(listName) {    
    return $.ajax({
        url: _spPageContextInfo.siteServerRelativeUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
}

//pass your list name
getListData("Custom List").done(function(data){
     data.d.results.forEach(function(item){ 
        console.log(item.Title );
     });
}).fail(function(data){
    console.log("something went wrong");
});

Mandatory reading - Write javascript promises

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.