How to read sharepoint list items from a specific folders using Javascript/Jquery through JSOM or REST?
Using JSOM or CSOM, you need to specify 'FileDirRef' property in CAML Query, and add 'RecursiveAll' scope:
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View Scope="RecursiveAll"> " +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name="FileDirRef" />" +
"<Value Type=\"Text\">yourFolderPath</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>');
function GetFolders() {
var oWeb = _spPageContextInfo.webAbsoluteUrl;
var URLC = oWeb + "/_api/web/lists/getByTitle('ListName')/items";
$.ajax({
url: URLC,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
$.each(data.d.results, function (index, item) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('ListName/ListFolder)/listitemallfields/",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
}
});
})
},
error: function (data) { }
});
}
You can use REST API to read list items from a specific folders using getfolderbyserverrelativeurl.
Refer below Code :
var folderRelativeUrl = "Relative_URL_Of_Your_Folder"; //here specify relative URL of your folder (e.g. '/Shared Documents')
getItemFromFolder().then(getItemFromFolderSuccess, getItemFromFolderFailed);
function getItemFromFolder(){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderRelativeUrl + "')/files?$expand=ListItemAllFields",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getItemFromFolderSuccess(data){
// success handler
var response = data.d.results; // This is Response Object from Server
}
function getItemFromFolderFailed(error){
// error handler code
}
Related
I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>
I am trying to post reply on a particular discussion of SharePoint online discussion board through REST API but unable to do it. I don't want to use SP.utilities as this REST API will be called from Android App.
Below is the code which I am implementing:
$.ajax({
url:"../_api/web/Lists/getbytitle(listname)/items?$filter=ParentItemID eq 40",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("Successfully posted!!");
},
error: function (error) {
alert("error");
console.log(JSON.stringify(error));
}
});
Instead of creating reply inside discussion, it is creating a new discussion item.
Any help will be highly appreciated.
For creating a message item (reply) in Discussion Board the following properties needs to be specified:
FileSystemObjectType for a message items needs to be set to 0
ContentTypeId- content type Id of message item
ParentItemID - discussion item (container for messages) id
Regarding ParentItemID property
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId>
}
Solution
The following example demonstrates how to to create a message (reply) in Discussion Board via SharePoint REST API.
For creating a message under a discussion item (folder) the following
approach is used: once message item is created, it's getting moved
under a discussion item
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}
I'm trying to use RESTful services to return all replies in a SharePoint sitefeed. Currently, I am successfully using this code to retrieve the sitefeed's posts:
function getFeed(){
var feed;
var reply;
var rCounter;
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/actor(item=#v)/feed?#v=%27https://<mysite>.sharepoint.com/<sitename>/newsfeed.aspx%27",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
myFeed = $(data);
console.log(myFeed);
for (i = 0; i < myFeed[0].d.SocialFeed.Threads.results.length; i++) {
feed = (myFeed[0].d.SocialFeed.Threads.results[i].RootPost.Text);
console.log(myFeed[0].d.SocialFeed.Threads.results[0].Actors.results[1].Name + ": " + feed);
if (myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length >0){
rCounter = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length;
for (j = 0; j < myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length; j++) {
rCounter--;
reply = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results[rCounter].Text;
console.log(reply);
}
}
console.log("* * * * * * * * *");
}
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
However, this gives me the posts but with only the two latest replies. According to this MSDN post, I need to use a POST method to get all replies and pass in the thread ID. So I made a new function:
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
When I run this new function, I get a 403 (FORBIDDEN) error. Can someone tell me what I'm doing wrong?
try passing headers like below.
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
I am trying to construct the correct URL to return the items in a SharePoint View using the REST api.
Using my browser and the following URL I can return the items in the list.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
And I can get the view definition using the following URL.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Views/getbytitle('Latest News')/
But I cannot figure out what I need to put at the end of that URL to actually get the items that are returned by the the View.
SP.View object does not contain any methods for manipulating list items. But SP.View object contains SP.View.viewQuery property that specifies the query that is used by the list view. That means the following approach could be used for retrieving list items for view:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query
How to return list items for a List View using REST API using JavaScript
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
Usage
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'Announcements','Latest News')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
I'm trying to post a wall message from a local desktop application (I can't use the FB JS SDK).
Here's a a snippet of my code
var url = "https://graph.facebook.com/me/feed";
var params = "access_token=" + token + "&message=" + encodeURI(text);
$.ajax({
crossDomain: true,
data: params,
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
The request ignores the message parameter.
I receive a list of feeds as it were a GET request.
I've tried to set the parameters as map but it didn't help.
BTW - when using CURL (in C++) i manage to post the data correctly.
Any ideas why it ignores the parameters?
I would put the "params" into the data element like so:
var url = "https://graph.facebook.com/me/feed";
$.ajax({
crossDomain: true,
data: { access_token: token, message: text },
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
Let jQuery encode the parameters from there.
Below worked fine in Jquery 1.6.4 + jquery.mobile-1.0rc2 by setting $.mobile.allowCrossDomainPages = true; in mobileinit bind
$.ajax( {
url : "https://graph.facebook.com/me/feed",
type : "POST",
data : "access_token=" + your_access_token + "&message=my first wall post",
cache : false,
success : function(res) {
if (!response || response.error) {
alert("Couldn't Publish Data");
} else {
alert("Message successfully posted to your wall");
}
},
error : function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
}
});