Methods

ajax

(source code)
ajax(settings)
Permits to do an Ajax request based on https://github.com/yanatan16/nanoajax for Browsers, and https://github.com/s-KaiNet/sp-request for NodeJS

Parameters:

Object
settings
(See options below)
String
settings.url
The url to call
String
settings.method Optional, Default: "GET"|"POST"
The HTTP Method ("GET" or "POST" if "body" is provided)
Object
settings.headers Optional
the headers
String
settings.body Optional
The data to send to the server
Function
settings.onprogress Optional, Default: function(event){}
Show the download/upload progress (within browser only)
Function
settings.getXHR Optional, Default: function(xhr){}
Pass the XMLHttpRequest object as a parameter (within browser only)

Returns:

Promise
resolve(responseText||responseXML), reject({response, statusCode, responseText})

Example:

// for a regular request
$SP().ajax({url:'https://my.web.site'}).then(function(data) { console.log(data) })

// if the URL contains /_api/ and if "Accept", "Content-Type" or "X-RequestDigest", then they are auto-defined

// (in browser) manipulate xhr for specific needs, like reading a remote file (based on https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data)
$SP().ajax({url:'https://url.com/file.png', getXHR:function(xhr){ xhr.responseType = 'arraybuffer' }}).then(function(data) {
  // ArrayBuffer result
  var blob = new Blob([data], {type: "image/png"});
  fileReader.readAsArrayBuffer(blob);
})

// (in browser) show progress on download, and cancel the download after 5 seconds
var _xhr;
$SP().ajax({
  url:'https://server/files/video.mp4',
  getXHR:function(xhr) {
    _xhr = xhr;
    xhr.responseType = 'arraybuffer'
  },
  onprogress:function(event) {
    console.log(event.loaded+" / "+event.total)
  }
});
setTimeout(function() { _xhr.abort() }, 5000); // abort after 5 seconds

// (in Node) to get the Buffer from a remote file we could use `encoding:null`
// ATTENTION: it will only work if the file is located on a Sharepoint; for other remote files, please use another library like `request`
sp.ajax({url:'https://my.web.site/lib/file.pdf', encoding:null}).then(data => {
  // 'data' is a Buffer
})

// for a CORS/cross-domain request you may need to use 'false' for 'Content-Type'
// ATTENTION: it will only work if the file is located on a Sharepoint; for other remote files, please use another library like `request`
$SP().ajax({url:'https://my.cross-domain.web/site', headers:{"Content-Type":false}}).then(function(data) { console.log(data) })

arrayBufferToBase64

(source code)
arrayBufferToBase64(arrayBuffer)
Permits to convert an array buffer to a Base64 string (source: https://gist.github.com/jonleighton/958841)

Parameters:

Array
arrayBuffer

Returns:

String
The base64 encoded-string

Example:

$SP().arrayBufferToBase64(*ArrayBuffer*); // -> *string*

arrayChunk

(source code)
arrayChunk(b, e)
Permits to cut an array into smaller blocks

Parameters:

Array
b
The array to split
Number
e
The size of each block

Returns:

Array
An array that contains several arrays with the required size

Example:

$SP().arrayChunk(["a","b","c","d","e","f","g","h"], 2); -> ["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"]

cloneObject

(source code)
cloneObject(deep, objectDestination, objectSource)
It will clone an object (source: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/24248152#comment75410509_24248152)

Parameters:

Boolean
deep Optional, Default: false
If we want a deep clone
Object
objectDestination
The object that will be extended
Object
objectSource
The object the copy

getLookup

(source code)
getLookup(str)
Split the ID and Value

Parameters:

String
str
The string to split

Returns:

Object
.id returns the ID (or an array of IDs), and .value returns the value (or an array of values)

Example:

$SP().getLookup("328;#Foo"); // --> {id:"328", value:"Foo"}
  $SP().getLookup("328;#Foo;#191;#Other Value"); // --> {id:["328", "191"], value:["Foo", "Other Value"]}
  $SP().getLookup("328"); // --> {id:"328", value:"328"}

getPeopleLookup

(source code)
getPeopleLookup(str)
When returning a people field from a list using 'expandUserField' to true, then this utility function will split into more friendly pieces

Parameters:

String
str
The string to split

Returns:

Object|Array
An object (or array of objects) with 'id', 'name', 'username', 'email'

Example:

$SP().getPeopleLookup("42;#Doe,, John,#i:0#.w|domain\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John"); // --> {id:"42", name:"Doe, John", username:'i:0#.w|domain\John_Doe', email:'John_Doe@Domain.com'}
  $SP().getPeopleLookup("42;#Doe,, John,#i:0#.w|domain\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John;#1981;#Doe,, Jane,#i:0#.w|domain\Jane_Doe,#Jane_Doe@Domain.com,#Jane_Doe@Domain.com,#Doe,, Jane"); // --> [ {id:"42", name:"Doe, John", username:'i:0#.w|domain\John_Doe', email:'John_Doe@Domain.com'}, {id:"1981", name:"Doe, Jane", username:'i:0#.w|domain\Jane_Doe', email:'Jane_Doe@Domain.com'} ]

getRequestDigest

(source code)
getRequestDigest(settings)
Retrieve a Request Digest (and it will change the value of document.querySelector("#__REQUESTDIGEST") when a new Request Digest is created)

Parameters:

Object
settings
String
settings.url Optional, Default: current
To check another URL (or if you use it on a Node server)
Boolean
settings.cache Optional, Default: true
TRUE to use the cache and/or the one into the page for the digest, FALSE to get a new one

Returns:

Promise
resolve(Request Digest), reject(reject from $SP().ajax())

Example:

$SP().getRequestDigest({cache:false}).then(function(digest) { console.log("The new digest is "+digest)})

getServerTime

(source code)
getServerTime(date, url)
Return the current server time (or convert the passed date)

Parameters:

Date
date Optional, Default: new Date()
You can send a Date object and it will be converted using the server time
String
url Optional, Default: "current website"
The url of the website

Returns:

Promise
resolve(DateInUTC), reject(error)

Example:

$SP().getServerTime().then(function(dateInUTC) {
    console.log("Server Time: "+dateInUTC);
  }, function(error) {
    console.log(error)
  })

getTimeZoneInfo

(source code)
getTimeZoneInfo(settings)
Permits to retrieve the TimeZone informations (ID, Description, XMLTZone) based on the server's timezone

Parameters:

Object
settings Optional
String
settings.url Optional, Default: "current website"

Returns:

Object
resolve({ID, Description, XMLTZone}), reject(error)

getURL

(source code)
getURL()
Return the current base URL website

Returns:

Promise
resolve(The current base URL website), reject(error)

hasREST

(source code)
hasREST(settings)
In the earlier version of SharePointPlus, this function was used to check if the REST API was available – these days I assume everyone is now using at least SharePoint 2013, so this function always returns TRUE – if you don't have REST API you can still define _SP_CACHE_HASREST["url to check"]=false

Parameters:

Object
settings
String
settings.url Optional, Default: current
To check another URL

Returns:

Promise
A resolved Promise that gives TRUE or FALSE

isSPO

(source code)
isSPO(settings)
Return TRUE if the SharePoint is SharePoint Online

Parameters:

Object
settings
String
settings.url Optional, Default: current
To check another URL

Returns:

Boolean
Return TRUE if it's SPO or FALSE if not, or NULL is not able to determine it

newGuid

(source code)
newGuid()
Create an unique GUID (based on Sharepoint function called SP.Guid.newGuid())

regionalDateFormat

(source code)
regionalDateFormat()
Provide the Date Format based on the user regional settings (YYYY for 4-digits Year, YY for 2-digits day, MM for 2-digits Month, M for 1-digit Month, DD for 2-digits day, D for 1-digit day) -- it's using the DatePicker iFrame (so an AJAX request)

Returns:

Promise
resolve(dateFormat), reject(error)

Example:

// you'll typically need that info when parsing a date from a Date Picker field from a form
  // we suppose here you're using momentjs
  // eg. we want to verify start date is before end date
  var startDate = $SP().formfields("Start Date").val();
  var endDate = $SP().formfields("End Date").val();
  $SP().regionalDateFormat().then(function(dateFormat) {
    // if the user settings are on French, then dateFormat = "DD/MM/YYYY"
    if (moment(startDate, dateFormat).isAfter(moment(endDate, dateFormat))) {
      alert("StartDate must be before EndDate!")
    }
  })

  // Here is also an example of how you can parse a string date
  // -> https://gist.github.com/Aymkdn/b17903cf7786578300f04f50460ebe96

regionalSettings

(source code)
regionalSettings()
Find the region settings (of the current user) defined with _layouts/regionalsetng.aspx?Type=User (lcid, cultureInfo, timeZone, calendar, alternateCalendar, workWeek, timeFormat..)

Returns:

Promise
resolve({lcid, cultureInfo, timeZone, calendar, alternateCalendar, workWeek:{days, firstDayOfWeek, firstWeekOfYear, startTime, endTime}}), reject(error)

Example:

$SP().regionalSettings().then(function(region) {
    // show the selected timezone, and the working days
    console.log("timeZone: "+region.timeZone);
    console.log("working days: "+region.workWeek.days.join(", "))
  }, function(error) {
    console.log(error)
  })

toDate

(source code)
toDate(textDate, forceUTC)
Change a Sharepoint date (as a string) to a Date Object

Parameters:

String
textDate
the Sharepoint date string
Boolean
forceUTC Optional, Default: false
Permits to force the reading of the date in UTC

Returns:

Date
the equivalent Date object for the Sharepoint date string passed

Example:

$SP().toDate("2012-10-31T00:00:00").getFullYear(); // 2012

toPeopleString

(source code)
toPeopleString(either, id, name, username, email)
Transform the result from a `$SP().getPeopleLookup()` to a string

Parameters:

Array|Object
either
a simple object, or an array of this object
Number
id
The UserID
String
name
The preferred name
String
username Optional
The username
String
email Optional
The user email

Returns:

String
the formatted string in the form "id;#name,#username,#email,#email,#name" (or just "id;#name" if no "username" is provided)

Example:

var person = $SP().getPeopleLookup("42;#Doe,, John,#domain\\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John"); // --> {id:"42", name:"Doe, John", username:'domain\\John_Doe', email:'John_Doe@Domain.com'}
  $SP().toPeopleString(person); // --> "42;#Doe,, John,#domain\\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John"

toSPDate

(source code)
toSPDate(dateObject, includeTime)
Change a Date object into a Sharepoint date string

Parameters:

Date
dateObject
The Date object you want to convert
Date
includeTime Optional, Default: false
By default the time is not returned (if the time appears then the WHERE clause will do a time comparison)

Returns:

String
the equivalent string for the Date object passed

Example:

$SP().toSPDate(new Date(2012,9,31), true); // --> "2012-10-31T00:00:00Z"
  $SP().toSPDate(new Date(2012,9,31)); // --> "2012-10-31"

toXSLString

(source code)
toXSLString(text)
Change a string into a XSL format string

Parameters:

String
text
The string to change

Returns:

String
the XSL version of the string passed

Example:

$SP().toXSLString("Big Title"); // --> "Big_x0020_Title"

webService

(source code)
webService(options, operation, service, properties, webURL, soapURL, soapAction)
Permits to directly deal with a WebService (similar to SPServices http://sympmarc.github.io/SPServices/core/web-services.html)

Parameters:

Object
options
String
operation
The method name to use (e.g. UpdateList, GetList, ....)
String
service
The name of the service (Lists, Versions, PublishedLinksService, ...) it's the ".asmx" name without the extension
Object
properties Optional, Default: {}
The properties to call
String
webURL Optional, Default: current website
The URL of the website
String|Boolean
soapURL Optional, Default: 'http://schemas.microsoft.com/sharepoint/soap/'
If the SOAP url is not the default one, then you can customize it... it will be send in the request's headers as "SOAPAction"
Boolean
soapAction Optional, Default: true
Some web services don't want the "SOAPAction" header

Returns:

Promise
resolve(responseBody), reject(see $SP().ajax())

Example:

$SP().webService({ // http://sympmarc.github.io/SPServices/core/web-services/Lists/UpdateList.html
  service:"Lists",
  operation:"Updatelist",
  webURL:"http://what.ever/"
  properties:{
    listName:"Test",
    listProperties:"...",
    newFields:"...",
    updateFields:"...",
    deleteFields:"...",
    listVersion:"..."
  }
}).then(function(response) {
  // do something with the response
}, function(error) {
  console.log("Error => ",error)
});

// to remove a person from a group
$SP().webService({
  service:"UserGroup",
  operation:"RemoveUserFromGroup",
  soapURL:"http://schemas.microsoft.com/sharepoint/soap/directory/",
  properties:{
    groupName:"Group",
    userLoginName:"domain\\user"
  }
}).then(function(response) {
  console.log("OK => ",response)
}, function(error) { console.log("Error => ",error) });

workflowStatusToText

(source code)
workflowStatusToText(code)
Return the text related to a workflow status code

Parameters:

String|Number
code
This is the code returned by a workflow

Example:

$SP().workflowStatusToText(2); // -> "In Progress"