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

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

Related

ValueError: Cannot use None as a query value django ajax

I want to show the dropdown list with data response via Ajax call. Everything is working fine but I am getting this ValueError: Cannot use None as a query value error.
view:
def load_brand(request):
if request.is_ajax():
term = request.GET.get('term')
brand = Brand.objects.all().filter(brand__icontains=term)
return JsonResponse(list(brand.values()), safe=False)
ajax:
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {id: item.id, text: item.brand};
})
};
}
},
minimumInputLength: 1
});
In your ajax call you have not send the data i.e : which user type inside select2 and you are accessing them i.e : request.GET.get('term') which is empty so your .filter(brand__icontains=term) giving you error because term value is null.
Instead you can add below as well in your ajax call :
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
data: function(params) {
var query = {
term: params.term, //this will be paass
type: 'public' //optional..
}
// Query parameters will be ?term=[values]&type=public
return query;
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
id: item.id,
text: item.brand
};
})
};
}
},
minimumInputLength: 1
});
Also , at your server end you can check if the term has any value i.e :
if term:
brand = Brand.objects.all().filter(brand__icontains=term)
For more information check this

Update SharePoint List Item using Rest API and HTML Input Element

I am having a difficult time trying to get my below script to work for updating items on my SharePoint list “ProjectTracker”. I researched and tried several similar methods, but I can’t seem to get the any script version to update the list item(s). I continually receive the SharePoint error message “value”: This type SP.ListItemEntityCollection does not support HTTP PATCH method.” Statue”:400,”statusText”:”Bad Request”}. I included a screen grab of the error and below is the script I am using.
Any help or advice will be greatly appreciated. Thank you in advance.
jQuery(document).on("click", '#UpdateListItem', function(){
UpdateListItem();
});//Button close
function UpdateListItem() {
var myID = $("#itemID").val();
var listName = "ProjectTracker";
var office = $("#uOffice").val();
var title = $("#uProjectTitle").val();
var priority = $("#uPriority").val();
var startDate = $("#uStartDate").val();
var assignedTo = $("#uAssignedTo").val();
var status = $("#uStatus").val();
var requestor = $("#uRequestor").val();
var item = {
"__metadata": { "type": "SP.Data.ProjectTrackerListItem" },
"Office": office,
"ProjectTitle": title,
"Priority": priority,
"StartDate": startDate,
"AssignedTo": assignedTo,
"Status": status,
"Requestor": requestor
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + myID + ")",
type: "POST",
data: JSON.stringify(item),
headers: {
contentType: "application/json;odata=verbose",
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method":"MERGE",
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Item Updated');
}
function onError(error) {
alert(JSON.stringify(error));
}
}//Function close
Please check list internalname and column internal name
For more details with AJAX call refer below age for full ajax call l.
https://sharepointmasterhub.blogspot.com/2020/12/sharepoint-crud-operations-with-rest-api.html?m=1#Update

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 can I get list items by view name, using REST API ajax?

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

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#.