Wednesday, 16 May 2018

How to Post Data to a SharePoint List with AngularJS - Easy Steps

Hello, good to see you here.
Be sure that it really is not so difficult to post data from a form to a SharePoint List. I would show you the steps and also give you the codes.
Just 5 Steps. Lets go!

Content:

If you have any issue though, just let me know. Use the comment box below or the form to left of this page.

Step 1: Create a SharePoint List 


Create a list in SharePoint and called CustomerDetails.
This list should contain the following fields three fields.
  • Firstname
  • Lastname
  • Address
We are keeping it very simple so you will understand exactly how it works.

Step 2: Add Bootstrap, AngularJS and JQuery


Create a html page and add AngularJS and BootStrap to the header like shown below:

<html>
<head>

<title>AngularJS Tutorial</title>
<script type="text/javascript" src="bootstrap.js"> </script>
<script type="application/javascript" src="jquery.min.js"></script>
<script type="application/javascript" src="angular.js"></script>
<script type="application/javascript" src="index.js"></script>

</head>

<body>
...
//We would place the form here
...
</body>

</html>
Listing 1: Add files in header section

Step 3: Add the html Form


Add the following html to the body of your page, in between the <body> and </body> tags. This is the form that would be filled to be submitted to the SharePoint list


<form name="userForm" ng-app="myapp" ng-controller="myController" >
  <div class="form-group">
 <label for="firstname">Firstname </label> 
 <input type="text" ng-model="Firstname" class="form-control" id="firstname" />    
  </div>
  <div class="form-group">
 <label for="lastname">Lastname:</label>
 <input type="text" ng-model="Lastname" class="form-control" id="lastname" />
  </div>
  <div class="form-group">
 <label for="address">Address:</label>
 <input type="text" ng-model="Address" class="form-control" id="address" />
  </div>
  <button type="submit" class="btn btn-primary"  ng-click="submitCustomer()" class="btn btn-default" data-dismiss="modal">Submit</button>
</form>    
Listing 2: Code the HTML Form

Step 4: Add the Script


Add the following code to your AngularJS script. Name this script index.js. It's a bit complicated but I want you to first try it, then I would explain how it works to you or help you debug any error you may be getting. Remember to link this script to your html page and place the two in the same folder


var myapp = angular.module('myapp', []);

myapp.controller('myController', function($q, $scope, $http){

 //add nomination to start workflow                                                      
 function getRequestDigest(){
   var deferred = $q.defer();   
     $http ({
     url: "RequestDigest url ", //Get this url from your IT department
     method: "POST",
     headers: {
     "Content-Type": "application/json; odata=verbose",
     "Accept": "application/json; odata=verbose"
     }
    }).success(function (response) {
     console.log('X-RequestDigest value:', response.d.GetContextWebInformation.FormDigestValue); 
     $scope.requestDigest = response.d.GetContextWebInformation.FormDigestValue;
     deferred.resolve(response.d);     
    }).error(function (err) {
     console.log('Error in POST request digest', err);
     deferred.reject(err);
    });
    return deferred.promise;
 }
 //digest end

 
 //FUNCTION TO POST ITEM TO THE DATABASE
 function AddCustomer(listName){
    $scope.submitSuccess=false;
    $scope.submitError = false;
    var deferred = $q.defer();
    var requestData;
    
    var  GetItemTypeForListName = function (name) {
   return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
    };
    
     var itemType = GetItemTypeForListName(listName);

    //JSON BODY OF THE REQUEST
    requestData = {
    "Title": $scope.Firstname,
    "LastNamePhonetic": $scope.Lastname,
    "WorkAddress": $scope.Address,
  __metadata : { type: itemType }
    };
  
    var postUrl = baseUrl + "_api/web/lists/getbytitle(listName)/items"; //Replace baseUrl
    var config = {
     headers: {
    "Content-Type": "application/json; odata=verbose",
    'Accept': 'application/json; odata=verbose',
    'X-RequestDigest': $scope.requestDigest
     }     
  };         
   console.log("requestDigest", $scope.requestDigest);
   
   $http.post (postUrl, JSON.stringify(requestData), config).then(function (data) {
      console.log("success", data);
      $scope.submitSuccess=true;
            
   },function(error){
      console.log("failed", error);
      $scope.submitError=true;
   });

   return deferred.promise;

 };       
 //END OF POST


 //button- generate new item in the list and run wf
  $scope.submitCustomer = function (){
    console.log("submitCustomer");
    var promise1 = getRequestDigest();
    promise1.then(function(){       //1st run the RequestDigest, then the AddCustomer
   AddCustomer("CustomerDetails");
    });
 }   
 //button end

});
Listing 3: Content of your index.js file

Step 5: Test your page!


Although it looks complicated, but it is really very simple. Trust me!

Go ahead to view the page.
Enter some items in the form and submit and check that the items gets inserted. Then go the list in SharePoint to make sure the item actually got inserted.

Let me know if you have challenges, I would be able to provide some guidance for you