How can I get list items by view name, using REST API ajax? - sharepoint-2013

I tried to get a list of items from the Sharepoint library by view name. I had ajax rest API URL:
url: webapp + "_api/web/list/getbytitle" + "('" + LibraryName + "')/View/getbytitle" +"('" + viewName + "')"
method:"GET"
header:"Accept":"application/json;odata=verbose
How can I get all the items in view name?

please refer the following code snippet to get items from specific view, Rest API not provider items endpoint return from a view directly.
So please do the following:
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:
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'MyList12','View1')
.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));
});
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);
});
}
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"
}
});
}
Same question has been answered here:
Using REST to fetch SharePoint View Items

Related

Getting list of Sharepoint Site Collections - OnPrem 2016. Console.log is empty

I'm tyring to get a list of all the site collections that users have permissions to access. My plan is to display these on the home page, to make it easy for them to navigate to each of their sites. I've tried the following code, but nothing form my API call is writing the the console. It's just blank. What am I missing with writing to the console? Is the name siteURL wrong?
'''
$.ajax({
url: "/_api/search/query?querytext='contentclass:sts_site'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var results = data.d.results;
var itemhtml = "";
$.each(results, function (index, dataRec) {
console.log(siteUrl);
});
},
error: function (data) {
(data);
}
})
'''
Here is a code snippet to get all site collection and print using Console.log:
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
//print sites info
searchSites(_spPageContextInfo.webAbsoluteUrl,
function(query){
var resultsCount = query.PrimaryQueryResult.RelevantResults.RowCount;
for(var i = 0; i < resultsCount;i++) {
var row = query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i];
var siteUrl = row.Cells.results[6].Value;
console.log(JSON.stringify(siteUrl));
}
},
function(error){
console.log(JSON.stringify(error));
}
);
});
function searchSites(webUrl,success, failure) {
var url = webUrl + "/_api/search/query?querytext='contentclass:sts_site'";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d.query);
},
error: function (data) {
failure(data);
}
});
}
</script>
Reference:
What is the REST endpoint URL to get list of site collections?

How to get the total number of Items in a specific view in a list using rest api

I have requirement to get the total number of items in a specific view
in a SharePoint list.
I am trying below end point but it is returning count of all item in a
list.
/_api/Web/Lists/GetByTitle('<list_name>')/Items
let say view name is XYZ and list name is ABC how to build a rest api
to get total count of items in XYZ view from ABC list?
To get the item count in a specific list view, firstly get the list view CAML Query, then use this CAML Query with Post Request in Rest API to return items, here is a code snippet for your reference:
<script type="text/javascript">
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'ABC','XYZ')
.done(function(data)
{
var itemsCount = data.d.results.length;
alert(itemsCount);
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
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);
});
}
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"
}
});
}
</script>
Reference:
Using REST to fetch SharePoint View Items
You can do it either way, using CAML Query and using same filters as list view or using filters in your Rest API URL.
For details please check https://sharepoint.stackexchange.com/a/266795/68021

django csrf error in fetch api ajax

I want to replace my jquery ajax code with es6 fetch api under django framework
this is my jquery ajax code
var csrf = $('meta[name="csrf_token"]').attr('value')
//comment vote
$("#comment_box").on('click', "a.vote-up", function() {
var voteID = parseInt(this.id.split("-")[1]);
$.ajax({
url : "/vote_json/",
type : "POST",
dataType: "json",
data : {
"comment_id": voteID,
"vote": $('#up-' + voteID).attr('value'),
csrfmiddlewaretoken: csrf
},
success : function(json) {
$('#up-' + voteID).html('<i class="chevron vote up icon"></i>' + json.vote);
$('#up-' + voteID).popup({
position : 'top center',
content : json.msg,
on : 'manual'
});
$('#up-' + voteID).popup('show');
setTimeout(function (){$('#up-' + voteID).popup('hide');}, 3000);
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
and this code is es6 fetch api
let csrf = document.querySelector('meta[name="csrf_token"]').getAttribute('value');
//comment vote
[].forEach.call(document.querySelectorAll('a.vote-up'), function (voteup) {
voteup.addEventListener('click', function () {
let voteid = parseInt(voteid.id.split("-")[1]);
fetch('/vote_json/', {
method: 'POST',
body: JSON.stringify({
comment_id: voteid,
vote: document.querySelector('#up-' + voteid).getAttribute('value'),
csrfmiddlewaretoken: csrf
})
}).then(function (response) {
return response.json();
}).then(function (json) {
document.querySelector('#up-' + voteid).innerHTML = '<i class="chevron vote up icon"></i>' + json.vote
document.querySelector('#up-' + voteid.popup({
position : 'top center',
content : json.msg,
on : 'manual'
}),
document.querySelector('#up-' + voteid).popup('show'),
setTimeout(function () {
document.querySelector('#up-' + voteid).popup('hide'), 3000
})
)
})
})
}
and this code is my view in django
def vote(request):
comment_pk = request.POST.get('comment_id')
vote = request.POST.get('vote')
comment = Comment.objects.get(pk=comment_pk)
if vote == 'true':
comment.up += 1
comment.save()
response_dict = dict(vote=comment.up)
elif vote == 'false':
comment.down -= 1
comment.save()
response_dict = dict(vote=comment.down)
return HttpResponse(json.dumps(response_dict), content_type='application/javascript')
the problem is that in jquery code everything is working but in es6 django responsed "CSRF verification failed. Request aborted." and I tested fetch ajax code in Get method without body block and another django view in this mode works fine
Copy pasted from here.
The solution was in the getCookie() method.
fetch("/graphql", {
method: "POST",
credentials: "same-origin",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
"Accept": "application/json",
'Content-Type': 'application/json'
},
body:JSON.stringify(query)
})
And of course the method has to be on the same page. Taken from Django Docs.
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

PhantomJs- Call WebService & Get data from that

I use by PhantomJs for connect to my WebService and Post data to WebService's Function for special computing. But i can't get result from WebService's Function.
bin.js:
var page = require('webpage').create();
var data = {
'str': 'sample string'
};
page.open('http://127.0.0.1/Service.asmx/HelloWorld', 'POST', data, function(status) {
// Get status
console.log('Status: ' + status);
// I want to get result
phantom.exit();
});
webService.asmx:
[WebMethod]
public string HelloWorld(string str)
{
return str;
}
I want something look like this in PhantomJs:
$.ajax({
type: "POST",
url: 'http://127.0.0.1/Service.asmx/HelloWorld',
data: {data: 'somethings'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
var result= data.d;
}
});
var webPage = require('webpage');
var page = webPage.create();
var postBody = 'param1=value1&param2=value2';
page.open('http:www.myservice.com/service', 'POST', postBody, function(status) {
console.log('Status: ' + status);
console.log('HTML Content: ' + page.content); // in case of an HTML response
console.log('JSON: ' + JSON.parse(page.plainText)); // in case of a JSON response
});
I solved my problem with search about "phantomjs in c#".
My solution is use of NReco.PhantomJS library in c#.

Getting oauth2 token with Angularjs returns me No 'grant_type' included in the request

i try to get a token from my django-rest-framework api and an angularjs client.
This is how i use the get token access:
var payload = {
username: 'seb',
password: 'aa',
grant_type: 'password',
client_id: consumerKey,
client_secret: consumerSecret
};
var r = $http.post('http://localhost:8000/oauth2/access_token',
payload);
r.success(function(response){
console.log(response.token);
});
I've updated my headers like this:
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
unfortunately it returns me {"error_description": "No 'grant_type' included in the request.", "error": "invalid_request"}
playing with curl returns me the desired token :(
One would expect the payload to be able to exist as a Json object... but alas it requires formData type content. The clue was in your line
'application/x-www-form-urlencoded';
Hence OAuth provider is expecting the data as form based. So your payload would need to be this:
payload = "grant_type=password" + "&username=seb" + "&password=aa" +
"&client_id=" + consumerKey +
"&client_secret=" + consumerSecret;
This is a simple HttpService implementation I put together.
angular.module("services").factory("HttpService", ["$q", "$http", function ($q, $http) {
var httpSvc = {};
httpSvc.Url = "";
httpSvc.ContentType = "application/x-www-form-urlencoded";
httpSvc.JsonPayload = {};
//execute login
httpSvc.HttpPost = function () {
var deferred = $q.defer();
appLogger.conlog(httpSvc.JsonPayload);
//Http Post method
$http({
method: "POST",
url: httpSvc.Url,
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
"Content-Type": httpSvc.ContentType
},
data: httpSvc.JsonPayload //post data
}).success(function (data, status, headers, config) {
deferred.resolve({ data: data, status: status, headers: headers, config: config }); //result
}).error(function (data, status, headers, config) {
deferred.reject({ data: data, status: status, headers: headers, config: config }); //result
});
appLogger.conlog(deferred.promise);
//return the callback promise
return deferred.promise;
};
return httpSvc;
}]);
Just inject it into a module and use it like so
var oauth2Payload = {
grant_type: "password",
username: userName,
password: password,
client_id: appConfig.clientId
};
httpSvc.JsonPayload = oauth2Payload;
httpSvc.Url = sysConfig.tokenUrl;
httpSvc.HttpPost().then(function (response) {
var data = response.data;
appLogger.conlog("access_token:\r\n" + data.access_token);
appLogger.conlog("refresh_token:\r\n" + data.refresh_token);
$cookies.refresh_token = data.refresh_token;
appLogger.conlog(data);
deferred.resolve("ok");
}, function (errResponse) {
var data = errResponse.data;
appLogger.conlog(data);
deferred.resolve("error");
});