3

I want to create one common jquery library to work with REST queries in sharepoint. I have two files.

  1. REST_Operations.js
  2. consumer.js

In REST_Operations.js I am writing rest queries with deferred object as follows.

"use strict";
var RESTQueries = RESTQueries || {};
RESTQueries.getItemsFromList = function(){
    var deferred = $.Deferred();
    var execute = function(){
        $.ajax({
            url:"https://mysiteurl/sites/practice/_api/web/lists/getByTitle('Pages')/items",
            method:'GET',
            headers:{Accept:'application/json; odata=verbose'},
            success:function(data){
                deferred.resolve(data);
            },
            error:function(err){
                deferred.reject(err);
            }
        });
        return deferred;
    };

    return {
        execute:execute
    }
}();

RESTQueries.readItemsFromList = function(){
    RESTQueries.getItemsFromList.execute().promise().then(function(data){
        return data;    
    });

}

If i put console.log in then() function, data is coming properly. I have one more js file, cosumer.js, in that i am calling readItemsFromList as follows

var items = RESTQueries.readItemsFromList();

so my idea is items variable should contain the json object or result for the rest query. But if i put console.log(items), output is coming as undefined. How to get the json object in the items variable?

If I try with following code

RESTQueries.readItemsFromList = function(siteUrl,listName){
    return (RESTQueries.getItemsFromList.execute(siteUrl,listName).promise().then(function(data){
            console.log(data);
           return data; 
    }));
}

it is giving me different kind of object. Find the below screenshot. enter image description here

2

Add return in front off RESTQueries.getItemsFromList, like this:

RESTQueries.readItemsFromList = function(){
    return RESTQueries.getItemsFromList.execute().promise().then(function(data){
        return data;    
    });
}
  • I tried as per your suggestion. I am trying to get like this var items= RESTQueries.readItemsFromList() but return item is giving some different kind of object, and if i put console.log inside of then function, this statement was executed after the items object. see my edited question for output – Mihir Nov 14 '14 at 8:51
  • 2
    The object you get back is the promise, not the data. It's not synchronous, so you would do something like RESTQueries.readItemsFromList().then(function(data) { console.log(data); }); – eirikb Nov 14 '14 at 8:54
  • Yeah here I am getting data without any issues. My intention is make all queries as library. So finally people should write a single line of code as var items = RESTQueries.readItemsFromList();. People should not worry about the promises. You got what I am saying!! – Mihir Nov 14 '14 at 9:07
  • 2
    Sounds like you want to use $.ajax({async:false}) and drop promises. While that is possible, IMHO it's a bad idea. Returning a promise is a good thing, even if it adds some lines to the library usage. E.g., what would you do if you wanted to bundle several requests and wait for all of them to finish? With a promise that is superdupereasy – eirikb Nov 14 '14 at 9:11
  • Yeah understood. actually i got it work like RESTQueries.getItemsFromList.execute('https://mysiteurl/sites/practice','Pages').then(function(data){console.log(data);}); But I am just searching is there any way like that. – Mihir Nov 14 '14 at 9:17
0

I have one question, you are developing for APP in office 365 ?

If yes, continue reading the post. If not, explain to me how you want to do that maybe will help you :)

I'm sure you must put the AJAX that runs synchronously.

try with this code below:

"use strict";

var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var AppUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var par_url, par_list; // parameters to set in ajax;
function getItemsFromList(){
    var deferred = $.Deferred();
        $.ajax({
            url: String.format("{0}/_api/sp.appcontextsite(@target)/web/lists/getByTitle('{1}')/items?@target='{3}'", AppUrl, par_list, par_url); 
            method:'GET',
            headers:{Accept:'application/json; odata=verbose'},
            success:function(data){
                deferred.resolve(data);
            },
            error:function(err){
                deferred.reject(err);
            }
        });
        return deferred;

};

function readItemsFromList(url, page){
  var scriptbase = hostUrl + "/_layouts/15/";
  // allow cross-domain between host and app!
  $.getScript(scriptbase + "SP.RequestExecutor.js", function () {
    par_url = url;
    par_page = page;
    var processGETitems = new getItemsFromList();
    processGETitems.done(function (result) {
            return result;
    });
    processGETitems.fail(function (result) {
            return result;
    });
  });   
}


function getQueryStringParameter(urlParameterKey) {
    var params = document.URL.split('?')[1].split('&');
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split('=');
        if (singleParam[0] == urlParameterKey) return decodeURIComponent(singleParam[1]);
    }
}

And now, you can call the method:

var items = getItemsFromList('http://yourdomain.com','ListName'); //return [Object] if not, maybe your url or list not exist.

Please let know if I helped you.

Thanks, b1c10

References: http://weshackett.com/2014/02/sp-requestexecutor-cross-domain-calls-using-rest-gotcha/

Note: If you use domain sphost different of hosturl that you set, you will get acess denied by security do Office 365 ! :/

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.