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

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?

Related

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

Google Storage + JQuery-File-Upload + Django + Signed URL, how should I change submit() and relevant options?

I have the following js code and it uses the signed-url api to get signed urls for uploading content to google storage via Django api.
When I use it with the following code :
xhr.open("PUT", data.signed_url);
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
It works fine and I am able to upload to Google Storage very large files. But obviously, when I do that, I cannot use any progress-bar features of jquery-file-upload.
Can you please suggest on how I should alter the data.submit(), where shall I put it, and how should I change the options or settings prior to submitting. Should I be overriding add or submit callback ?
I feel that there is a missing support for Google Storage with Jquery-file-upload as the only example covers only obsolute Google Blobstore in the following link : https://github.com/blueimp/jQuery-File-Upload/wiki/Google-App-Engine
$("#fileupload").fileupload({
dataType: 'json',
type: 'PUT',
sequentialUploads: true,
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
primary_data: data,
data: formData
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
console.log("With credentials");
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
console.log("With domainrequest");
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
console.log("With null");
xhr = null;
}
//What shall I do to make the following work for uploading GS
this.primary_data.url = data.signed_url;
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.submit();
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
} else {
alert("Failed to upload 1: " + status);
}
};
xhr.onerror = () => {
alert("Failed to upload 2");
};
//When the code below uncommented, it uploads to GS succesfully.
//xhr.setRequestHeader('Content-Type', file.type);
//xhr.send(file);
});
});
},
Also this is my cors setup for the GS Bucket.
[
{
"origin": ["*"],
"responseHeader": ["Content-Type", "Access-Control-Allow-Origin"],
"method": ["GET", "PUT", "OPTIONS"],
"maxAgeSeconds": 60
}
]

JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?

I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument.
How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ?
The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e, data) {
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
context: 'hello',
data: formData,
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
xhr = null;
}
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
//alert("File is uploaded");
} else {
}
};
xhr.onerror = () => {
};
xhr.setRequestHeader('Content-Type', file.type);
//data.submit();
});
});
},
If the $this = $(this) is defined prior to the $.each loop :
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) { ...
Then the following can be used to access the data in the parent function
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);

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

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