Tag Archives: AJAX

Creating a choice field in SPFx

When using the SharePoint Framework (SPFx), we can use spHttpClient to manage our REST calls. Creating new fields (columns) in lists is like using jQuery ajax methods, first we feed in the body of our call in JSON format.

const spOpts: ISPHttpClientOptions = {
      body: "{'Title': 'Group', 'FieldTypeKind':2,'Required':false, 'EnforceUniqueValues': 'false','StaticName': 'Group'}"
    };

Then we create the REST call and receive the response.

this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/GetByTitle('List Name')/Fields`, SPHttpClient.configurations.v1, spOpts)
      .then((response: SPHttpClientResponse) => {
        console.log(`Status code: ${response.status}`);
        console.log(`Status text: ${response.statusText}`);
        response.json().then((responseJSON: JSON) => {
          console.log(responseJSON);
        });
      });

However, we get an error when trying to create a choice column using the following body:


      body: "'Title': 'Behaviour', 'FieldTypeKind':6,'Required':true, 'EnforceUniqueValues': 'false', 'StaticName': 'Behaviour', Choices: ['Choice1', 'Choice2', 'Choice3'] }"

Error: “The property ‘Choices’ does not exist on type ‘SP.Field’. Make sure to only use property names that are defined by the type.”

To resolve this issue, we need to add the data type to the request, we structure the JSON in a different way (compared to jQuery ajax calls). This is the JSON required to create a choice column:

body: {'@odata.type': 'SP.FieldChoice','Title': 'Behaviour', 'FieldTypeKind':6,'Required':true, 'EnforceUniqueValues': 'false', 'StaticName': 'Behaviour', Choices: ['Choice1', 'Choice2', 'Choice3'] }

Hope someone finds this useful and saves you a lot of time!

JavaScript Client Object Model in SharePoint 2013

SharePoint 2013 has a new and more complete JavaScript Client Object Model API. Some of the additional functionality is using social networking.

Using the JS COM, followers can be pulled from SharePoint for the current user or a specific user. This might be used for creating a new social networking interface

My Followers

First load JQuery and the SharePoint 2013 JavaScript functions. The JavaScript functions are loaded on the page so it is just a case of waiting for specific functions to be loaded before the script will work correctly (see below):

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
	SP.SOD.executeFunc('userprofile', 'SP.UserProfiles', function () {
		tonyishereGetUserProfileProperties();
	});
});

Once the functions are loaded, the People manager object can be created. The example below was taken from the Micrsoft site and modified, this is a great resource if you are starting out with the client object model.

http://msdn.microsoft.com/en-us/library/office/jj679673.aspx

function tonyishereGetUserProfileProperties() {
    // Get the current client context.
    var clientContext = SP.ClientContext.get_current();
    // Get the PeopleManager instance.
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    // Get the people who are following the current user.
    Followers = peopleManager.getMyFollowers();
    clientContext.load(Followers);
    // Send the request to the server.
    clientContext.executeQueryAsync(displayFollowers, requestFailed)
}

Once the object has been loaded successfully, functions can be run to pull out the required data. In the example below, the data is stored in a string which is then displayed as HTML in a div using JQuery.

function displayFollowers() {
    var results = Followers.getEnumerator();
	var myFollowers = "Followers<br />";
    while (results.moveNext()) {
    var person = results.get_current();
		myFollowers = myFollowers + "<br />" + person.get_displayName();
    }
	jQuery("#MyFollowers").html(myFollowers);
}

The script was added to the page without the use of Visual Studio or SharePoint Designer 2013. The script was inserted using the Script Editor web part. This web part runs client side code such as HTML and JavaScript.

Script Editor

The same methods can be used to pull out a whole host of data from the social aspects of SharePoint 2013 including the profile picture, display name, hash tags and trending topics.

Profile web part

Using XSLT, AJAX and jQuery to improve OOTB SharePoint Lists

Using XSL can completely change the way that any standard list view is displayed. There is a great video from Laura Rogers demonstrating what can be done with the XSLT List View in SharePoint Designer here.

XSLT
You can also build your own XSL sheets and use them in the style library by linking them in the web part properties.

Here is a standard web part view of a custom list:

Here is a standard web part view with custom XSL applied:

COM, jQuery and AJAX
Calling the SharePoint Client Object model with JavaScript, we can add items to the list without refreshing the page.
Inside the web part’s AJAX settings we can set the auto refresh so the list displays the new item (again without refreshing the page).
In this example, jQuery sets a fade-in animated gif to show the item being added to the list once send has been pressed. The fade-out effect is applied to the gif once success has been returned to the JavaScript function.
Building solutions like this can create complete customisable solutions using only custom lists in a modern integrated (no refresh) style.