javascript

javascript rest

Sharepoint REST

By On 19/02/2024

PnP references

msdn PNP

Get field in list

/_api/Web/Lists/getbytitle('Pages')/Fields?$select=InternalName,Id,Hidden,TypeAsString,Required&$filter=InternalName eq 'Title'

Get list content types

Get contentType fields

/_api/Web/Lists/getbytitle('Pages')/ContentTypes('0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390028D78BF8D3054E38BEF0590B43C4BA0E00572E4F21E9A2274ABC0C3A6B4238D562')/fields?$filter=(Hidden eq false)and (Group ne '_Hidden')&$select= InternalName,Hidden,Required,Title,TypeAsString,Required,Id,Group

Query search

/_api/search/query?querytext='Path:https://mcn365.sharepoint.com/sites/a_IntranetPays_42/sitePages/*'&selectproperties='Title,Path'

/_api/search/query?querytext='owstaxIdJiveTags:GP0*+OR+owstaxIdJiveCategories:GP0*'&rowsperpage=0&rowlimit=5&selectproperties='Title%2cowstaxIdJiveCategories%2cowstaxIdJiveTags'&sortlist='Rank:descending%2cmodifiedby:ascending'&clienttype='ContentSearchRegular'">https://mcncs36sddcsdcsint.com/sites/a_IntranetPays_42/_api/search/query?querytext='owstaxIdJiveTags:GP0*+OR+owstaxIdJiveCategories:GP0*'&rowsperpage=0&rowlimit=5&selectproperties='Title%2cowstaxIdJiveCategories%2cowstaxIdJiveTags'&sortlist='Rank:descending%2cmodifiedby:ascending'&clienttype='ContentSearchRegular'

test code

/_api/Web/Lists/getbytitle('Pages')/ContentTypes('0x010100C568DB52D9D0A1d37AF390028D78BF8D3054E38BEF0590B43C4BA0E00572E4F21E9A2274ABC0C3A6B4238D562')/fields?$filter=(Hidden eq false)and (Group ne '_Hidden')&$select= InternalName,Hidden,Required,Title,TypeAsString,Required,Id,Group

query user multi

/_api/web/lists/getbytitle('ResponsableRegions')/items(1)?$select=ResponsablesRegions/EMail,Id&$expand=ResponsablesRegions

get fields

/_api/web/lists/GetByTitle('Liste des chantiers')/fields?$filter=Hidden eq false&$orderby=Title&$select=Title,InternalName,TypeAsString,Hidden

Get Sharepoint Audit Logs

By On 05/04/2023

Create certification for azure app

    
        # Create certificate
        $mycert = New-SelfSignedCertificate -DnsName "myCertificate.org" -CertStoreLocation "cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
        
        $mypwd = ConvertTo-SecureString -String "myCertificatePsw" -Force -AsPlainText
        # Export certificate to .pfx file
        $mycert | Export-PfxCertificate -FilePath myCertificate.pfx -Password $mypwd
        
        # Export certificate to .cer file
        $mycert | Export-Certificate -FilePath myCertificate.cer  
    

Connect to site

    
        $url = "https://m365x6422vvvvd.sharepoint.com/";
        $appId = "868d7a0c-a3dc-45af-b4a7-f72a70f61a60";
        $thumbprint = "A17177BB0E8A465F6AD08B0CEAE2F369C46D6481";
        $tenantId = "3533ab30-c2f0-48fd-b4c5-f5dc6ca77ec3"

        Connect-PnPOnline  -Url $url -Tenant $tenantId -Thumbprint $thumbprint -ClientId $appId
    

Export audit

premission required

Office 365 Management APIs (3) :: ActivityFeed.Read

possible filters

  • FilePreviewed
  • FileAccessed
  • SignInEvent
  • FileModifiedExtended
  • FileUploaded
  • PageViewed
  • PagePrefetched
  • FileCheckedIn
  • FileModified
  • FolderCreated
  • ListUpdated
  • ListViewed
    
        $ele = Get-PnPUnifiedAuditLog -ContentType SharePoint -StartTime (Get-Date).AddDays(-2) -EndTime (Get-Date).AddDays(-1)

        $ele = Get-PnPUnifiedAuditLog -ContentType SharePoint

        $ele = Get-PnPUnifiedAuditLog -ContentType SharePoint | Where-Object {$_.Operation -eq "PageViewed"} | Select-Object CreationTime,Operation,Workload,UserId,ObjectId,SourceFileName,SiteUrl,SourceFileExtension,SourceRelativeUrl

        $ele | Export-Csv -Path "Audit_3.csv" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"
    

with sharepoint search request

    
        kqlQuery = "ContentTypeId:0x0101009D1CB255DA76424F860D91F20E6C4118*";//news
        kqlQuery = "ContentTypeId:0x0101* language=fr ViewsLastMonths3=0";//documents
        kqlQuery = "ContentTypeId:0x0101* ViewsLifeTime=0";
        var seletvvv = "Title,ViewsLifeTimeUniqueUsers,ViewsLifeTime,language,Created,Size,Path,LastModifiedTime,ViewsLastMonths3,ViewsLastMonths3Unique,LastAnalyticsUpdateTime";

        &sortlist='Size:descending'
        &sortlist='ViewsLifeTime:descending'
    

How to resolve the 5000 item limit

By On 24/01/2022

     var firstItems = listLocation.web.getList(listLocation.listUri).items.select("ID").top(1).orderBy("Id").get();
     var lastItems = listLocation.web.getList(listLocation.listUri).items.select("ID").top(1).orderBy("Id", false).get(); 

    if (firstItems.length === 1 && lastItems.length === 1) {
      const firstId: number = firstItems[0].ID;
      const lastId: number = lastItems[0].ID;
      let startId = firstId;
      let endId = firstId + 5000;
      do {
        let mySites: ISite[] = await listLocation.web.getList(listLocation.listUri).items

          .select("ID", "Title", "Url")
          .filter(`Id ge ${startId} and Id lt ${endId} and ProprietairesPeople/Id eq ${userId}`)
          .expand('ProprietairesPeople')
          .orderBy("Title")
          .top(5000)
          .getAll(); 

          allMySites.push(...mySites);
          startId = startId + 5000;
          endId = endId + 5000;
      }
      while (endId < lastId);
    }
    return allMySites;

Add User To Group With Rest

By On 20/09/2021

Add User To Sharepoint Group With Rest

 


var fdi = fdi || {};

fdi.post = function(request, data, urlWeb, retFunction, expecedcode=200, odata="verbose"){
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo?&select=FormDigestValue";
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=nometadata");
	xhr.onload = function () {
		if (xhr.status === 200) {
			console.log(url + " : success");
			var d = JSON.parse(xhr.responseText);
            console.dir(d.FormDigestValue);

            var viewXml =  "" +
                    "" +
                    "" +
                    "" +
                    "";
            
            var req = { "query" :{"__metadata": { "type": "SP.CamlQuery" }, "ViewXml": viewXml}};
            var xhrPOST = new XMLHttpRequest();
            var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(5)/users";
            //debugger;
            xhrPOST.open('POST', reqUrl, true);
            xhrPOST.setRequestHeader("Accept", "application/json; odata=" + odata);
            xhrPOST.setRequestHeader("content-type", "application/json; odata=" + odata);
            xhrPOST.setRequestHeader("X-RequestDigest", d.FormDigestValue);

            console.log("onload");
            xhrPOST.onload = function () {
                
            console.log("onload ok");
                console.dir(JSON.parse(xhrPOST.responseText));
            }
			
			var metadata = {  
    __metadata: {  
        'type': 'SP.User'  
    },  
    LoginName: 'i:0#.f|membership|fred.ddiet@test.com'  
};  JSON.stringify(metadata)
            xhrPOST.send(JSON.stringify(metadata));
            console.log("sent");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);			
		}
	};
    xhr.send();
};

fdi.post();

Get Sharepoint List Items Count

By On 02/04/2021

Get Sharepoint list Items count


var xhr = new XMLHttpRequest();
console.clear();
var url = "https://mySiteUrl";
xhr.open('GET', url + "/_api/web/Lists/getbytitle('TheListName')?$select=ItemCount,Title");

xhr.setRequestHeader("Accept", "application/json; odata=verbose");
 
xhr.onload = function () {
	if (xhr.status === 200) {
		var kk = JSON.parse(xhr.responseText);
		console.dir(kk.d.Title + " Item Count : " + kk.d.ItemCount);
	}
	else {
		console.dir(xhr);
		alert('Request failed. Returned status of ' + xhr.status);
	}
};
xhr.send();

In your browser you must be your your site url, push key F12 paste above code in console, en push enter

Listitemscount

fr

Sharepoint Rest Caml Query

By On 06/01/2021

Use Sharepoint REST api to do a caml query

 


fdi.post = function(request, data, urlWeb, retFunction, expecedcode=200, odata="verbose"){
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo?&select=FormDigestValue";
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=nometadata");
	xhr.onload = function (data) {
		if (xhr.status === 200) {
			console.log(url + " : success");
			var d = JSON.parse(xhr.responseText);
            console.dir(d.FormDigestValue);

            var viewXml =  "<View>" +
                    "<Query>" +
                    "<Where></Where>" +
                    "</Query>" +
                    "</View>";
            
            var req = { "query" :{"__metadata": { "type": "SP.CamlQuery" }, "ViewXml": viewXml}};
            var xhrPOST = new XMLHttpRequest();
            var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Catalogue Produits')/GetItems";
            debugger;
            xhrPOST.open('POST', reqUrl, true);
            xhrPOST.setRequestHeader("Accept", "application/json; odata=" + odata);
            xhrPOST.setRequestHeader("content-type", "application/json; odata=" + odata);
            xhrPOST.setRequestHeader("X-RequestDigest", d.FormDigestValue);

            console.log("onload");
            xhrPOST.onload = function () {
                
            console.log("onload ok");
                console.dir(JSON.parse(xhrPOST.responseText));
            }
            xhrPOST.send(JSON.stringify(req));
            console.log("sent");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);			
		}
	};
    xhr.send();
};

Sharepoint Modern Update listItem

By On 09/12/2020

Update list in a modern site, getting formDigestValue


console.clear();
var dataToManage = {};
function getItemTypeForListName(listTitle, returnfct){
	var xhr = new XMLHttpRequest();
	var url = _spPageContextInfo.webAbsoluteUrl;
	if (url === "undefined") {
		console.log("_spPageContextInfo.webAbsoluteUrl undefined");
		url = "http://siteUrl";
	}
	
	xhr.open('GET', url + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName");
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.onload = function () {
		if (xhr.status === 200) {
			var kk = JSON.parse(xhr.responseText);
			console.dir(kk.d.ListItemEntityTypeFullName);
                        var returnValue = {};
			returnValue.ListItemEntityTypeFullName = kk.d.ListItemEntityTypeFullName;
			if(returnfct != null)
				returnfct(returnValue);
		}
		else {
			console.dir(xhr);
			alert('Request failed.  Returned status of ' + xhr.status);
		}
	};
	xhr.send();
}

//get FormDigestValue to do POST requests
function GetDisgestValue(returnFct){
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo";
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.setRequestHeader("content-type", "application/json; odata=verbose");
	xhr.onload = function (data) {
		if (xhr.status === 200) {
			console.log("success");
			var d = JSON.parse(xhr.responseText);
			console.dir(d.d.GetContextWebInformation.FormDigestValue);
			dataToManage.FormDigestValue = d.d.GetContextWebInformation.FormDigestValue;
			returnFct(d.d.GetContextWebInformation.FormDigestValue);
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);			
		}
	};
	xhr.send();
}

function UpdateListItem(){
	
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle" + 
	"('" + dataToManage.listName + "')/items("+dataToManage.itemId+")";
	
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.setRequestHeader("X-RequestDigest", dataToManage.FormDigestValue );
	xhr.setRequestHeader("content-type", "application/json; odata=verbose");
	xhr.setRequestHeader("X-HTTP-Method", "MERGE");
	xhr.setRequestHeader("If-Match", "*");
	
	xhr.onload = function () {
		if (xhr.status === 204) {
			console.log("success");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);
			
		}
	};
	var str = JSON.stringify(dataToManage.item);
	xhr.send(str);
} 

function withDigestValue(formDigestValue){
	console.log("formDigestValue : " + formDigestValue);	
}

function getListDatas(data){
	console.log(data.ListItemEntityTypeFullName);
	dataToManage.listName = "aTest";//list title to update
	dataToManage.itemId = 1;//id of the item to update
	dataToManage.item = {
        "__metadata": { "type": data.ListItemEntityTypeFullName },
		"Title": "new title"//new fields values
    };
	GetDisgestValue(UpdateListItem);
}

getItemTypeForListName("atest", getListDatas);

Invalid Client Query Exception

By On 07/07/2020

Microsoft.SharePoint.Client.InvalidClientQueryException A type named 'SP.Data' could not be resolved by the model. When a model is available, each type name must resolve to a valid type

 

get the correct ListItemEntityTypeFullName 

 

 




var xhr = new XMLHttpRequest();
var url = _spPageContextInfo.webAbsoluteUrl;
if (url === "undefined") {
    console.log("_spPageContextInfo.webAbsoluteUrl undefined");
    url = "http://siteUrl";
}
//xhr.open('GET', url +"/_api/web/Lists?$select=Id,Title,Hidden,ItemCount");
xhr.open('GET', url + "/_api/lists/getbytitle('Campaigns')?$select=ListItemEntityTypeFullName");
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
xhr.onload = function () {
    if (xhr.status === 200) {
        var kk = JSON.parse(xhr.responseText);
        console.dir(kk);
    }
    else {
        console.dir(xhr);
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

Sharepoint Update Item With REST

By On 07/07/2020

Sharepoint update an item with REST no jquery

 


console.clear();
function UpdateListItem(listName){
    var listItemId=176;
    var itemType = "SP.Data.SurveysListItem";//GetItemTypeForListName(listName);
	//debugger;
    var item = {
        "__metadata": { "type": itemType },
		"LaunchReportingFlag": "0"
    };
	/*
		"Reporting": ""		
	
	*/
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items("+listItemId+")";
	var requestdigest = document.getElementById("__REQUESTDIGEST");
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.setRequestHeader("X-RequestDigest", requestdigest.value);
	xhr.setRequestHeader("content-type", "application/json; odata=verbose");
	xhr.setRequestHeader("X-HTTP-Method", "MERGE");
	xhr.setRequestHeader("If-Match", "*");
	
	xhr.onload = function () {
		if (xhr.status === 204) {
			console.log("success");
		}
		else {
			console.log("error");
			console.log(xhr.status);
			console.dir(xhr);
			console.dir(xhr.responseText);
			
		}
	};
	xhr.send(JSON.stringify(item));
}
 
UpdateListItem("Campaigns");


getItemTypeForListName


function getItemTypeForListName(listTitle){
	var xhr = new XMLHttpRequest();
	var url = _spPageContextInfo.webAbsoluteUrl;
	if (url === "undefined") {
		console.log("_spPageContextInfo.webAbsoluteUrl undefined");
		url = "http://siteUrl";
	}
	//xhr.open('GET', url +"/_api/web/Lists?$select=Id,Title,Hidden,ItemCount");
	xhr.open('GET', url + "/_api/web/lists/getbytitle('" + listTitle + "')/?$select=ListItemEntityTypeFullName");
	xhr.setRequestHeader("Accept", "application/json; odata=verbose");
	xhr.onload = function () {
		if (xhr.status === 200) {
			var kk = JSON.parse(xhr.responseText);
			console.dir(kk.d.ListItemEntityTypeFullName);
		}
		else {
			console.dir(xhr);
			alert('Request failed.  Returned status of ' + xhr.status);
		}
	};
	xhr.send();
}

Sharepoint REST query Search

By On 28/06/2020

use rest api to search items in sharepoint

var fdi = {};
fdi.search = function(url, query, target, selectProperties){
    var req = url + "/_api/search/query?querytext='" + query + "'&selectproperties='"+ selectProperties +"'&sortlist='LastModifiedTime:descending'&rowlimit=500";

    //&rowsperpage=0&rowlimit=5
    var xhr = new XMLHttpRequest();

    fdi.fdilog(req);
    xhr.open('GET', req);
    xhr.setRequestHeader("Accept", "application/json; odata=verbose");
    xhr.onload = function () {
        if (xhr.status === 200) {
            var kk = JSON.parse(xhr.responseText);
            fdi.lastQuery = req;
            fdi.lastResult = kk;

            fdi.fdilog(kk.d);
            //debugger;
            
            fdi.fdilog(kk.d.query.PrimaryQueryResult.RelevantResults.Table.Rows);//,TypeAsString,Title,Hidden,Required,Group
            fdi.fdilog("RowCount : " + kk.d.query.PrimaryQueryResult.RelevantResults.RowCount);
            fdi.fdilog("TotalRows : " + kk.d.query.PrimaryQueryResult.RelevantResults.TotalRows);
           var rows = kk.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
            var datas = [];
            var columns = selectProperties.split(",");
            for(var i = 0 ; i < rows.length ; i++){
                var tar = {};
                tar.rowNum = i;
                for(var j = 0 ; j < columns.length ; j++){
                        var found = false;
                    for(var k = 0 ; k < rows[i].Cells.results.length ; k++){
                        if(rows[i].Cells.results[k].Key == columns[j]){

                            found = true;
                            tar[columns[j]] = rows[i].Cells.results[k].Value;
                        }
                        if(!found)
                            tar[columns[j]] = "";
                    }
                }
                datas.push(tar);
//rows[i].Cells.results[1].Key
            }
            fdi.fdilog(datas);
            fdi.createTable("rowNum," + selectProperties, datas, target, "#EEEEEE");
        }
        else {
            fdi.fdilog(req);
            fdi.fdilog(xhr);
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send();//send request
}

use as below

var reqvvv = "ContentTypeId:0x010056313CD55A8D274EB8FAF2CA0B228BCA00AAEACC42FC8BD24797DEF621447F7D00*";
var seletvvv = "Title,Path,RefinableString20,RefinableString23,RefinableString24,RefinableString25,RefinableDecimal02,RefinableDecimal03,RefinableDecimal04,LastModifiedTime,ListItemID";

fdi.search("https://aSite/sites/Dev", reqvvv, "fdiOutPut", seletvvv); 

 

Sharepointsearchapiquery

Display in a table


fdi.createTable = function( columns, datas, target, backGroundColor){
    if(fdi.isNullOrEmpty(target))
        return;
    
    // var targetDiv = document.getElementsByClassName("SPCanvas");
    // targetDiv[0];
    var targetDiv = document.getElementById(target);
    targetDiv.innerHTML = "";
	var tbl = document.createElement('table');
    var att = document.createAttribute("class");
    
    //var thead = document.createElement('thead');
    var tr1 = document.createElement('tr');
    
    var columnArray = columns.split(",");
    var att = null;
    for(var i = 0 ; i < columnArray.length ; i++){
        var th = document.createElement('th');
        fdi.fdidebuglog(columnArray[i]);
		th.innerText = columnArray[i];
        att = document.createAttribute("style");
        att.value = "border:1px solid #000;width:230px";
        th.setAttributeNode(att);
		tr1.appendChild(th);
    }
    tbl.appendChild(tr1);

    for(var j = 0 ; j < datas.length ; j++){
        var tr2 = document.createElement('tr');
        //background-color: #EEEEEE
        if(j % 2 == 0 && typeof(backGroundColor) !== "undefined"){
            att = document.createAttribute("style");
            att.value = "background-color:" + backGroundColor + ";";
            tr2.setAttributeNode(att);
        }
        for(var i = 0 ; i < columnArray.length ; i++){
            var td = document.createElement('td');
            td.innerText = datas[j][columnArray[i]];
            att = document.createAttribute("style");
            att.value = "border:1px solid #000;width:230px";
            td.setAttributeNode(att);
            tr2.appendChild(td);
        }        
        tbl.appendChild(tr2);
    }
    
    targetDiv.appendChild(tbl);
}

 

full script

Sharepoint Query Search By UTC Date

By On 09/12/2019

Sharepoint query search by date (UTC date type)
 
When your field is DateOnly => 12/12/2019, search service will store it like : 2019-12-11T23:00:00.0000000Z
 
In your regionnal settings, you can see -1
 
 
So in your query to retrieve you should substract one hour
 
                    
                        var aDate = new Date('2019-12-12);
                        var offset = new Date().getTimezoneOffset();
                        console.log("offset : " + offset);//in my case, offset is -60
                        console.dir(aDate);
                        aDate.setMinutes(aDate.getMinutes() + offset);
                        console.dir(aDate);
                        /_api/search/query='MnpDate:aDate.toISOString()';
                        // aDate : 2019-12-11T23:00:00.0000000Z
                    
                

Sharepoint Query Using REST

By On 27/11/2019

Here is my page to develop my REST queries

if my query returns an object, it will display all properties of my obj, as in navigation console (console.dir(obj);)

if my query returns an array it will display all properties in input : "show properties'

 

complete code to add in a script editor webpart :see script

 

Querycontenttypesfieds

 

queries samples : 


/_api/web/lists(guid'0E12917B-80F9-4765-8612-22A9AB467123')/items?$select=AssignedTo,Title&$orderby=DueDate desc&$filter=RelaunchDate eq null and Status eq 'In Progress'


/_api/web/getlist('/sites/csc-dev/Lists/myLMist')/fields?$select=Group,InternalName,Title,TypeAsString,Hidden


/_api/web/getlist('/sites/csc-dev/Lists/vdfdfvf')/fields?$select=Group,InternalName,Title,TypeAsString,Hidden&$filter=Hidden eq false and TypeAsString ne 'Computed' and startswith(InternalName, '_') eq false&$orderby=TypeAsString


/_api/web/getlist('/sites/csc-dev/Lists/myLMist')/fields?$select=Group,InternalName,Title,TypeAsString,Hidden


/_api/web/lists(guid'0E12917B-80F9-4765-8612-22A9AB46784E')/items?$select=AssignedTo/EMail,Created,Author/EMail,Body,DueDate,,ID,IsGroup,Modified,Editor/EMail,StartDate,Status,stepName,TaskGroup/EMail,TaskIdentifier,TaskProcessed,TaskProcessedBy/Title,TaskProcessedBy/Id,TaskProcessedBy/EMail,Title,WFFormFieldStepType,WFInstance&$orderby=DueDate desc&$filter=RelaunchDate eq null and Status eq 'In Progress'&$expand=Author,Editor,AssignedTo,TaskProcessedBy,TaskGroup

USER

{
Title: string;
EMail: string;
Id: number;
}

Hide Sharepoint Top Nav

By On 30/10/2019

Add in your query string fdiedit=1 to show the top vanigation
<style>
#SearchBox{
display: none;
}
#gdocSearchBox {
display: block;
}
#s4-ribbonrow{
display: none;
}
#suiteBarTop{
display: none;
}
#SearchBox{
display: none;
}
 
#DeltaTopNavigation .root.ms-core-listMenu-root.static {
margin-top: 10px;
}
 
#s4-titlerow {
margin-top: 0px;
margin-bottom: 0px;
padding-top: 0px;
padding-bottom: 1px;
height: 20px;
}
.ms-breadcrumb-top{
display: flex;
}
</style>
 
<script type="text/javascript">
 
function showSpStandard() {//show top nav
jq("#suiteBarTop").show();
jq("#s4-ribbonrow").show();
jq("#SearchBox").show();
jq("#DeltaPageStatusBar").show();
jq("#s4-titlerow").show();
jq("#suiteBarTop").show();
jq(".root.ms-core-listMenu-root.static").show();
}
function getUrlVars() {//get query strings
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
 
function fdiShowEdit(){//if query string
var canEdit = getUrlVars()["fdiedit"];
if(canEdit == 1)
showSpStandard();
}
 
_spBodyOnLoadFunctionNames.push("fdiShowEdit");
</script>
You can put this script in a script editor webpart or in master page 

Sharepoint Rest Query List

By On 21/09/2019

Query sharepoint list with REST

 

use this end point to query your list http://test/sites/test/_api/Web/Lists/getbytitle('vvv')/items?$select=&$filter= Title eq 'entite du ga 1'

Example : http://test01/sites/test01/_api/Web/Lists/getbytitle('Aliste')/items?$select=Title,ID,Author/Title&$expand=Author&$filter= Title eq 'entite du toto 1'

to order by : &$orderby= Employee asc

to order by : &$orderby= Employee desc

to limit number of items returned : $top 5

to use paging : $skip 5

new paging mode add in your first query  &$skiptoken=Paged=TRUE in your response, you will receive next page query in odata.nextLink as below

Nextlink

/_api/Web/Lists/getbytitle(%27Initiatives%27)/items?%24skiptoken=Paged%3dTRUE%26p_ID%3d266&%24select=Title%2cID&%24orderby=ID+desc&p_ID=268&%24Top=3

 

expand lookup fields : $expand=city&$select=city/Id

 

viewfields : $select= Title, ID

filter : $filter=Title eq 'mon noeud' and ID ne 1

 

Numeric comparisons

  • Lt
  • Le
  • Gt
  • Ge
  • Eq
  • Ne
 

String comparisons

  • startsWith
  • substringof
  • Eq
  • Ne
 

Date and time functions

  • day()
  • month()
  • year()
  • hour()
  • minute()
  • second()

 

 

Querylist 1

 
 

html to query list

 

javascript to query list

 

css to query list

 

base html file

 

Full script to add in an Script Editor webpart

 

script without JQuery

SPField Set ShowInDisplayForm With Rest

By On 23/11/2018

function UpdateList(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getbytitle('Pages')/Fields(guid'f941f8cf-65d5-4cdb-bc6b-6fab7ea92bc3')/setshowindisplayform(false)",
type: "POST",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
alert('Success');
window.location.href=window.location.href;
},
error: function (data) {
console.dir(data);
}
});
}
UpdateList();

Sharepoint ajax Without Jquery

By On 16/11/2018

var xhr = new XMLHttpRequest();
var url = _spPageContextInfo.webAbsoluteUrl;
if (url === "undefined") {
console.log("_spPageContextInfo.webAbsoluteUrl undefined");
url = "http://siteUrl";
}
//xhr.open('GET', url +"/_api/web/Lists?$select=Id,Title,Hidden,ItemCount");
// /_api/web/lists/getbytitle('Projets')/items?$select=Title,ID,
xhr.open('GET', url + "/_api/web");
//prefer using odata=nometadata to get minimum values and upgrade performances
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
 
xhr.onload = function () {
if (xhr.status === 200) {
var kk = JSON.parse(xhr.responseText);
console.dir(kk);
}
else {
console.dir(xhr);
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
 

get script

Sharepoint Rest Base

By On 03/11/2018

//Copy file (copyTo) /_api/web/getFileByServerRelativeUrl('/sites/test/Template.xlsx')/copyTo(strNewUrl='/sites/test/Exports/Template_copy_5.xlsx',bOverWrite=true)
 
function getRequestData(req) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + req,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
console.dir(data);
},
error: function((data) {
console.dir(data);
}
});
}
getRequestData("/_api/web/Lists?$select=Id,Title,Hidden");
 
get script

Sharepoint Hide List With REST

By On 10/10/2018

function UpdateList(){
var listName="Acquisition";//set here liste title
var list = {
"__metadata": { "type": 'SP.List' },
"Hidden": true//Set here visibility : true == hidden
};
 
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(list),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
alert('Success');
window.location.href=window.location.href;//reload the page
},
error: function (data) {
console.dir(data);
}
});
}
UpdateList();
 
 

REST get Lists From Current Web

By On 08/10/2018

function getlists() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
var lists = data.d.results;
console.clear();
console.dir(lists);
for (var i = 0 ; i < lists.length ; i++) {
var lst = lists[i];
//console.dir(lst);
$.ajax({
async: false,
headers: { "accept": "application/json; odata=verbose" },
method: "GET",
url: lst.RootFolder.__deferred.uri,
success: function (data) {
// get the rootFolder
var folder = data.d;
console.log("Title : " + lst.Title + "; RootFolder :" + folder.ServerRelativeUrl
+ "; Hidden :" + lst.Hidden + "; ItemCount :" + lst.ItemCount + "; LastItemModifiedDate :" + lst.LastItemModifiedDate
+ "; BaseTemplate :" + lst.BaseTemplate);
}
});
 
}
},
error: function (data) {
console.log(data);
}
});
}
get the code only

Display Spfield from SPList

By On 29/09/2018

function getListFields() {
var listTitle = "Pages";
var showHidden = false;
var outPut = $("#fdiOutput");
var addOutput = outPut != null && (outPut.length > 0)? true : false;
var tbl = "<table class='fdi-table'>";
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('" + listTitle + "')/Fields",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
},
success: function (response) {
console.log(response);
if (addOutput)
tbl += "<tr><th>InternalName</th><th>Hidden</th><th>TypeAsString</th><th>Title</th></tr>";
for (var i = 0 ; i < response.d.results.length ; i++) {
var field = response.d.results[i];
if (!showHidden && field.Hidden) {
continue;
}
console.log(field.InternalName + " ; " + field.Hidden + " ; " + field.TypeAsString + " ; " + field.DisplayName);
if (addOutput)
tbl += '<tr><td>' + field.InternalName + '</td><td>' + field.Hidden + '</td><td>' + field.TypeAsString + '</td><td>' + field.Title + '</td></tr>';
}
tbl += "</table>";
if (addOutput)
$("#fdiOutput").append(tbl);
},
error: function (data) {
console.log("error getListFields " + listTitle);
console.log(data);
debugger;
}
});
}

get script