Sunday, July 30, 2017

What's new in authentication for SharePoint 2013

User authentication and authorization in SharePoint 2013

source: https://technet.microsoft.com/en-in/library/jj219758.aspx
User authentication in SharePoint 2013 is the process that verifies the identity of a user who requests access to a SharePoint web application. An authentication provider issues the authenticated user a security token that encapsulates a set of claims-based assertions about the user and is used to verify a set of permissions that are assigned to the user. User authorization in SharePoint 2013 is the process that determines the users who can perform defined operations on a specified resource within a SharePoint web application. SharePoint 2013 supports user authentication based on the following methods:
  • Windows claims
  • Security Assertion Markup Language (SAML)-based claims
  • Forms-based authentication claims
These claims-based authentication methods are now the recommended authentication methods for SharePoint 2013.

The app authentication and server-to-server authentication features of SharePoint 2013 require claims-based authentication. Because of this, claims-based authentication is the default for new web applications in SharePoint 2013. When you create a web application in Central Administration, you can only specify authentication methods for claims-based authentication. Although Windows Classic mode authentication is still available in SharePoint 2013 and can be configured through Windows PowerShell, we recommend that you use claims-based authentication. Windows Classic mode authentication is deprecated in SharePoint 2013.

Improvements in claims infrastructure

SharePoint 2013 also includes the following improvements in claims authentication infrastructure:
  • Easier migration from classic mode to Windows-based claims mode with the new Convert-SPWebApplication Windows PowerShell cmdlet
    Migration can be run against each content database and each web application. This is in contrast to SharePoint 2010 Products, in which the migration was run against each web application. For more information, see Migrate from classic-mode to claims-based authentication in SharePoint 2013.
  • Login tokens are now cached in the new Distributed Cache Service
    SharePoint 2013 uses a new Distributed Cache Service to cache login tokens. In SharePoint 2010 Products, the login token is stored in the memory of each web front-end server. Each time a user accesses a specific web front-end server, it needs to authenticate. If you use network load balancers in front of your web front-ends, users need to authenticate for each web front-end server that is accessed behind the load balancer, causing possible multiple re-authentications. To avoid re-authentication and its delay, it is recommended to enable and configure load balancer affinity (also known as sticky sessions). By storing the login tokens in the Distributed Cache Service in SharePoint 2013, the configuration of affinity in your load balancing solution is no longer required. There are also scale-out benefits and less memory utilization in the web front-ends because of a dedicated cache service.
  • More logging makes the troubleshooting of authentication issues easier
    SharePoint 2013 has much more logging to help you troubleshoot authentication issues. Examples of enhanced logging support are the following:
    • Separate categorized-claims related logs for each authentication mode
    • Information about adding and removing FedAuth cookies from the Distributed Cache Service
    • Information about the reason why a FedAuth cookie could not be used, such as a cookie expiration or a failure to decrypt
    • Information about where authentication requests are redirected
    • Information about the failures of user migration in a specific site collection

Server-to-server authentication

SharePoint 2013 extends OAuth to implement a server-to-server authentication protocol that can be used by services such as SharePoint 2013 to authenticate other services such as Exchange Server 2013 or Lync Server 2013 or services that are compliant with the server-to-server authentication protocol.
SharePoint 2013 has a dedicated local server-to-server security token service (STS) that provides server-to-server security tokens that contain user identity claims to enable cross-server authenticated access. These user identity claims are used by the other service to lookup the user against its own identity provider. A trust established between the local STS (the SharePoint 2013 server-to-server STS) and other server-to-server compliant services (the Exchange Server 2013 or Lync Server 2013 server-to-server STS) is the key functionality that makes server-to-server possible. For on-premises deployments, you configure the JavaScript Object Notation (JSON) metadata endpoint of the other server-to-server compliant service to establish this trust relationship. For online services, an instance of the Azure Access Control Service (ACS) acts as a trust broker to enable cross-server communications among the three types of servers.
The new server-to-server STS in SharePoint 2013 issues access tokens for server-to-server authentication. In SharePoint 2013 (and also in SharePoint 2010 Products), trusted identity providers that are compliant with the WS-Federation protocol are supported. However, the new server-to-server STS in SharePoint 2013 performs only the functionality that enables temporary access tokens to access other services such as Exchange Server 2013 and Lync Server 2013. The server-to-server STS is not used for user authentication and is not listed on the user sign-in page, the Authentication Provider UI in Central Administration, or in the People Picker in SharePoint 2013 Products.

App authentication

SharePoint 2013 uses OAuth 2.0 to authorize requests by apps in the SharePoint Store and App Catalog to access SharePoint resources on behalf of a user. The user grants permission to apps in the SharePoint Store and App Catalog to access SharePoint resources on the user's behalf when they are installed. For example, a user installs an app from the SharePoint Store. A SharePoint site contains an embedded HTML inline frame (IFRAME) that the app renders and that requires the app to access a user list. When a Web browser displays the site, the app then calls back to the server running SharePoint 2013 to access the list on behalf of the user. After the app obtains the data from the list, it displays the contents of the IFRAME.
The app authentication process in SharePoint 2013 uses OAuth to verify a claim that an app makes and assert that the app can act on behalf of an authenticated user. In SharePoint 2013, an instance of the Azure ACS acts as the app identity provider. You can also use app authentication without ACS. The authorization process verifies that an authenticated app has permission to perform a defined operation or to access a specified resource.

Sunday, July 23, 2017

Nintex form javascript code(NDP)


 var listName = 'Approval Limits';
 var taskListName = 'NDPTasks';

 var ndpList = 'List Name';
 var ndpListUrl ='Item URL';
 var requestor ='Requestor';

 var approvers = [];
 
NWF$(document).ready(function()
{NWF$(".apnl").hide();
NWF$(".bpnl").hide();
var isContainDispForm = ndpListUrl.indexOf("DispForm");if(isContainDispForm > -1)
{
  ndpListUrl = ndpListUrl.substring(0,isContainDispForm);}
var isEditMode = document.location.pathname.indexOf("/EditForm.aspx") > -1;
var isDispMode = document.location.pathname.indexOf("/DispForm.aspx") > -1;
if(isEditMode)
{
 ClearAllFields();
 GetApproversInAppLimits();

 GetAllTasksComments();
}
 var checked =  NWF$('#' + TabControl).find("input:checked").val();
 if(!checked)
 {
  NWF$('.AppPnlClass').hide();
 } });
 
 NWF$('#' + TabControl).change(function() {
  var checked =  NWF$('#' + TabControl).find("input:checked").val();
  if(checked == 'Approval')
  {
    NWF$('.AppPnlClass').show();
  }
   
 });

 function DisplaySavePnlToInitaitorREQ()
 {
  var isREQ =  NWF$('#' +REQ).val();
  var isSubmitForApproval =  NWF$('#' +SubForApproval).val();
  var currentUid = _spPageContextInfo.userId;
 
  if((isSubmitForApproval == 'No') && (currentUid == initiatorId))
  {
   NWF$('.pnlSaveCss').show();
  }
  else
  {
   NWF$('.pnlSaveCss').hide();
   NWF$('.ms-cui-ctl-large').eq(0).hide();    

  }
 
 
  if((currentUid == initiatorId) && (isREQ == 'Yes') && (isSubmitForApproval == 'Yes'))
  {
   NWF$('.pnlSaveCss').show();
   NWF$('.btnSubmitWFCss').hide();
   NWF$('.REQCss').hide();
   NWF$('.btnSubmitWFCssAppUI').show();
   NWF$('.ApproveBtnPnlClass').hide();
   NWF$("#"+NotionalVal).prop('readonly', true);
   NWF$("#"+NotionalVal).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 
  }
  else if(isSubmitForApproval == 'Yes')
  {
    NWF$('.pnlSaveCss').hide();
    NWF$('.inputControlCss').attr('style', 'background-color: #e5e9ec !important; border:none !important;');
    NWF$('.inputControlCss').prop('readonly', true);
    NWF$('.ms-cui-ctl-large').eq(0).hide();      NWF$('#'+TitleText).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:310px');
   

 NWF$('#aspnetForm select').attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+NotionalVal).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+ddlProductA).attr('disabled',true);
 NWF$('#'+productddlB).attr('disabled',true);
 NWF$('#'+ddlProductA).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+productddlB).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+BuyRadioBtn).find('input[type="radio"]').attr('disabled',true);
 NWF$('#'+deal18Radio).find('input[type="radio"]').attr('disabled',true);
 NWF$('#'+startDt).attr('disabled',true);
 NWF$('#'+endDt).attr('disabled',true);
 NWF$('#'+startDt).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+endDt).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+ NDPFormLogBox).closest('tr').find('div[id$="_inplacerte"]').eq(0).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 NWF$('#'+ NDPFormLogBox).closest('tr').find('div[id$="_inplacerte"]').eq(0).attr("contentEditable","false");
 NWF$('.propertysheet').hide();
 NWF$('.nf-attachmentsLink').hide();
 NWF$('.ui-datepicker-trigger').hide();

  NWF$('#'+bkddl).hide();
  NWF$('.bkcss').hide();
  NWF$('.productddl').hide();

  NWF$('#'+ddlProductA).hide();
  NWF$('#'+productddlB).hide();
 
  NWF$('.ms-rtestate-field').eq(0).attr('style', 'background-color: #e5e9ec !important; border:none !important;');
 
 NWF$('#'+NotionalVal).prop('readonly', true);
 NWF$('#'+TitleText).prop('readonly', true);

var isReviewStart = NWF$('#'+isRevStart).val();
  if(isReviewStart == 'Yes')
  {
     NWF$('.reviewPnlClass').show();
     NWF$('.ApproveBtnPnlClass').hide();  
  }
  else
  {
     NWF$('.ApproveBtnPnlClass').show();  
     NWF$('.reviewPnlClass').hide();
  }

   
  }
 
 
 }


 var getInitiatorIditems; var initiatorId;


function GetInitiatorIdForSubmitForAppWFBtn()
{
 var ctx = new SP.ClientContext.get_current();
 var oList = ctx.get_web().get_lists().getByTitle(ndpList);
 var ID = getParam("ID");
 var camlQuery = new SP.CamlQuery();
 var query = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>"+ID+"</Value></Eq></Where>";
     query += "<ViewFields> <FieldRef Name='ID' /><FieldRef Name='Author' /><FieldRef Name='Status' /></ViewFields></View></Query>";
 camlQuery.set_viewXml(query);
 getInitiatorIditems = oList.getItems(camlQuery);
 ctx.load(getInitiatorIditems);
 ctx.executeQueryAsync(OnSuccessGetInitiatorId,OnFailGetInitiatorId);

}
function OnSuccessGetInitiatorId()
{
 var count = getInitiatorIditems.get_count();
 if(count>0)
 {
 
  var items = getInitiatorIditems.getEnumerator();
  while (items.moveNext())
     {
     var listItem = items.get_current();
     initiatorId = listItem.get_item("Author").get_lookupId();
  var statusValue = listItem.get_item("Status");
  NWF$('#'+FinalApproval).val(statusValue);
     DisplaySavePnlToInitaitorREQ();
  }
 }
}

function OnFailGetInitiatorId()
{

}

 function RedirectToAllitemsView()
 {
     window.location = ndpListUrl;
 }



 NWF.FormFiller.Events.RegisterAfterReady(function ()
 {
    var isNewMode = document.location.pathname.indexOf("/NewForm.aspx") > -1;
    var isEditMode = document.location.pathname.indexOf("/EditForm.aspx") > -1;
    var isDispMode = document.location.pathname.indexOf("/DispForm.aspx") > -1;
    NWF$('.btnSubmitWFCssAppUI').hide();

 if(isNewMode)
 {
  try
  {
        CheckForRequestorNameInAppLimits();
  }
  catch(e)
  {
   alert("Something wrong went...");
  }
 }

 if(isEditMode)
 {
 try
 {
      DisplayPanalCheckForApproval();

    GetApproversOutCome();
    SP.SOD.executeOrDelayUntilScriptLoaded(GetInitiatorIdForSubmitForAppWFBtn,"sp.js");
 
   var isSubmitForApproval =  NWF$('#' +SubForApproval).val();
   var isREQ =  NWF$('#' +REQ).val();
 if((isSubmitForApproval == 'Yes') && (isREQ == 'No'))
   {
  NWF$('.nf-textbox-wrapper').eq(0).attr('style', 'top: -5px !important;');
  NWF$('.nf-textbox-wrapper').eq(11).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(2).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(3).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(4).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(5).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(7).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(8).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(9).attr('style', 'top: -3px !important;');
  NWF$('.nf-textbox-wrapper').eq(10).attr('style', 'top: -3px !important;');
   }
   else if((isSubmitForApproval == 'Yes') && (isREQ == 'Yes'))
   {
    NWF$('.nf-textbox-wrapper').eq(0).attr('style', 'top: 0px !important;');
    NWF$('.nf-textbox-wrapper').eq(11).attr('style', 'top: -3px !important;');
   }
 }
   catch(e)
 {
  alert("Something wrong went...");
 }
 }
 });





 function MakeTextReadOnly()
 {

 NWF$('#'+App1).prop("readonly", true);
 NWF$('#'+App2).prop("readonly", true);
 NWF$('#'+App3).prop("readonly", true);
 NWF$('#'+App4).prop("readonly", true);
 NWF$('#'+Rev1).prop("readonly", true);
 NWF$('#'+Rev2).prop("readonly", true);  
 NWF$('#'+App1).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+App2).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+App3).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+App4).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+Rev1).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');
 NWF$('#'+Rev2).attr('style', 'background-color: #e5e9ec !important; border:none !important; width:210px !important');

 NWF$('#'+out1).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out2).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out3).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out4).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out5).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');
 NWF$('#'+out6).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important');

 NWF$('#'+FinalApproval).attr('style', 'background-color: #e4e4e4 !important; border:none !important; width:175px !important; font-weight: bold !important;');  
 NWF$('#'+FinalApproval).prop("readonly", true);  }
 
 var itemAppLimits; var notionalVal;


 function GetApproversInAppLimits()
 {
  notionalVal = NWF$('#' + NotionalVal).val();
  var context  = new SP.ClientContext.get_current();
  var list     = context.get_web().get_lists().getByTitle(listName);
  var camlQuery = new SP.CamlQuery();
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
  var initiatorID = NWF$('.ms-subtleLink').eq(0).attr('href').split('=')[1];
 
 var query ="<View><Query><Where><And><Leq><FieldRef Name='Notional_x0020_Value_x003e_'  /><Value Type='Currency'>"+notionalVal+"</Value>";
    query += "</Leq><And><Geq><FieldRef Name='Notional_x0020_Value_x003c__x003'  /><Value Type='Currency'>"+notionalVal+"</Value>";
    query += "</Geq><Eq><FieldRef Name='TraderID' /><Value Type='Text'>"+initiatorID+"</Value></Eq></And></And></Where></Query></View>";
 
  camlQuery.set_viewXml(query);
  itemAppLimits = list.getItems(camlQuery);
  context.load(itemAppLimits);
  context.executeQueryAsync(onSuccesAppLimitsCall, OnFaiAppLimtslCall);
  }

 var app1;
 function onSuccesAppLimitsCall(sender, args)
 {  
   var count = itemAppLimits.get_count();
   var userId;
   if(count > 0)
   {
     var items = itemAppLimits.getEnumerator();
     while (items.moveNext())
     {
    var listItem = items.get_current();
   
     app1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Appr");
   
    if(app1)
    {
     app1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Appr").get_lookupValue();
  userId = listItem.get_item("_x0031_st_x0020_Level_x0020_Appr").get_lookupId();
     NWF$('#' + App1).val(app1);
  approvers.push(userId+";"+app1+";app1");
    }
    else
      NWF$('#' + App1).val("");
 
    var app2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Appr");
    if(app2)
    {
      app2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Appr").get_lookupValue();
   userId = listItem.get_item("_x0032_nd_x0020_Level_x0020_Appr").get_lookupId();
      NWF$('#' + App2).val(app2);
   approvers.push(userId+";"+app2+";app2");
    }
    else
     NWF$('#' + App2).val("");
 
    var app3 = listItem.get_item("_x0033_rd_x0020_Level_x0020_Appr");
    if(app3)
    {
     app3 = listItem.get_item("_x0033_rd_x0020_Level_x0020_Appr").get_lookupValue();
  userId = listItem.get_item("_x0033_rd_x0020_Level_x0020_Appr").get_lookupId();
     NWF$('#' + App3).val(app3);
  approvers.push(userId+";"+app3+";app3");
    }
    else
     NWF$('#' + App3).val("");
 
    var app4 = listItem.get_item("_x0034_th_x0020_Level_x0020_Appr");
    if(app4)
    {
      app4 = listItem.get_item("_x0034_th_x0020_Level_x0020_Appr").get_lookupValue();
   userId = listItem.get_item("_x0034_th_x0020_Level_x0020_Appr").get_lookupId();
      NWF$('#' + App4).val(app4);
   approvers.push(userId+";"+app4+";app4");
    }
    else
    NWF$('#' + App4).val("");
 
       var rev1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Revi");
    if(rev1)
    {
     rev1 = listItem.get_item("_x0031_st_x0020_Level_x0020_Revi").get_lookupValue();
  userId = listItem.get_item("_x0031_st_x0020_Level_x0020_Revi").get_lookupId();
     NWF$('#' + Rev1).val(rev1);
  approvers.push(userId+";"+rev1+";rev1");
    }
    else
     NWF$('#' + Rev1).val("");
 
    var rev2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Revi");
    if(rev2)
    {
      rev2 = listItem.get_item("_x0032_nd_x0020_Level_x0020_Revi").get_lookupValue();
   userId = listItem.get_item("_x0032_nd_x0020_Level_x0020_Revi").get_lookupId();
      NWF$('#' + Rev2).val(rev2);
   approvers.push(userId+";"+rev2+";rev2");
    }
    else
     NWF$('#' + Rev2).val("");     }
   
   }
 
   MakeTextReadOnly();
 }
 function OnFaiAppLimtslCall(sender, args)
 { }



 var finalApprovers =[]; var appName;


 function ClearAllFields()
 {
  NWF$('#' + App1).val("");
  NWF$('#' + App2).val("");
  NWF$('#' + App3).val("");
  NWF$('#' + App4).val("");
  NWF$('#' + Rev1).val("");
  NWF$('#' + Rev2).val("");
 }

 function SetWFApproversOutcome()
 {
   var i; var j; var WFOut;

    for(i = 0; i < approvers.length; i++)
    {
        for(j = 0; j < WFUsers.length; j++)
        {
             appName = approvers[i].split(';')[0];
             if(appName == WFUsers[j])
              {
      var reviewer = approvers[i].split(';')[2];
      if(reviewer == "rev1")
      {
      if(WFUsersOutcome[j] == "Approve")
      {
    NWF$(".revCss1").val("Reviewed");
   }
      else
      {
    NWF$(".revCss1").val(WFUsersOutcome[j]);
   }
      }
      else if(reviewer == "rev2")
      {
      if(WFUsersOutcome[j] == "Approve")
      {
    NWF$(".revCss2").val("Reviewed");
    }
      else
      {
    NWF$(".revCss2").val(WFUsersOutcome[j]);
   }
      }
      else
      {                
     var apps = "outCss"+(i+1);
     if(WFUsersOutcome[j] == "Approve")
     {
      NWF$("."+apps).val("Approved");
     }
     else
    {
     NWF$("."+apps).val(WFUsersOutcome[j]);
     }
   
      }
                  break;
              }
        }
 
  if(WFUsersOutcome[j])
  { WFOut = WFUsersOutcome[j]; }
  else{ WFOut ='0';}
 
  finalApprovers.push({
      key:  approvers[i].split(';')[0],
      value:WFOut,
      UName: approvers[i].split(';')[1],
   type: approvers[i].split(';')[2]
   });
    console.log(finalApprovers);
  }
   NWF$('#'+out1).prop("readonly", true);
   NWF$('#'+out2).prop("readonly", true);
   NWF$('#'+out3).prop("readonly", true);
   NWF$('#'+out4).prop("readonly", true);
   NWF$('#'+out5).prop("readonly", true);
   NWF$('#'+out6).prop("readonly", true);

 }  
 
 var outcomeItems; var outcomeResult;

 function GetApproversOutCome(userId)
 {
  var ID = getParam("ID");
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(taskListName);
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
  var camlQuery = new SP.CamlQuery();
 
  var query  = "<View><Query><Where><Eq><FieldRef Name='WorkflowItemId' /><Value Type='Text'>"+ID+"</Value></Eq></Where>";
       query += "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy></Query></View>";  
  camlQuery.set_viewXml(query);
  outcomeItems = list.getItems(camlQuery);
  ctx.load(outcomeItems);
  ctx.executeQueryAsync(onSuccesApproversOutComeCall,onfailOutComeCall);
 }

 var WFUsers = [];
 var WFUsersOutcome = [];


 function onSuccesApproversOutComeCall()
 {
   var count = outcomeItems.get_count();
   var userId;
   if(count > 0)
   {
     var items = outcomeItems.getEnumerator();
     while (items.moveNext())
     {
    var listItem = items.get_current();
    outcomeResult = listItem.get_item("WorkflowOutcome");
    var uId  = listItem.get_item("AssignedTo").get_lookupId();
    WFUsers.push(uId);
    WFUsersOutcome.push(outcomeResult);
     }
  try
  {
     SetWFApproversOutcome();
  }
    catch(e)
    {
     alert("Something went wrong... ");
    }
   }
 }
 function onfailOutComeCall()
 {
 }
  function getParam(param) {
  var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for (var i=0;i<url.length;i++) {
         var params = url[i].split("=");
         if(params[0] == param)
          return params[1];
  }
 }
 
  var pendingItems; var taskItemId;
 
 function DisplayPanalCheckForApproval()
 {
  var ID = getParam("ID");
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(taskListName);
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
  var camlQuery = new SP.CamlQuery();
 
 var query = "<View><Query><Where><And><Eq><FieldRef Name='AssignedTo' LookupId='True'/><Value Type='User'>"+_spPageContextInfo.userId+"</Value></Eq><And><Eq><FieldRef Name='WorkflowOutcome' />";
        query += "<Value Type='Text'>Pending</Value></Eq><Eq><FieldRef Name='WorkflowItemId' /><Value Type='Text'>"+ID+"</Value></Eq></And></And>";
  query += "</Where></Query></View>";
   
  camlQuery.set_viewXml(query);
  pendingItems = list.getItems(camlQuery);
     ctx.load(pendingItems);
     ctx.executeQueryAsync(onSuccesPendingTasksCall, OnFailPendingTasksCall);
 
 }


 function onSuccesPendingTasksCall()
 {
  var count = pendingItems.get_count();
  if(count > 0)
  {
  var items = pendingItems.getEnumerator();
  while (items.moveNext())
  {
    var listItem = items.get_current();
    taskItemId = listItem.get_id();
 
  }
   
   NWF$(".ApprovalPnlClass").show();
   NWF$('#'+Appbtn).val("1");
  }
  else
  {
   NWF$(".ApprovalPnlClass").hide();
   NWF$('#'+Appbtn).val("0");
  }
 }
 function OnFailPendingTasksCall()
 {}
   

//-------------------------------Tasks Logs ---------------------------
var tasklistItems;
function GetAllTasksComments()
{
  var ID = getParam("ID");
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(taskListName);
  var camlQuery = new SP.CamlQuery();
  var query = "<View><Query><Where><Eq><FieldRef Name='WorkflowItemId'/><Value Type='text'>"+ID+"</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
      query += "<ViewFields><FieldRef Name='Title' /><FieldRef Name='AssignedTo' /><FieldRef Name='ApproverComments' /><FieldRef Name='WorkflowOutcome' /></ViewFields></Query></View>";
  camlQuery.set_viewXml(query);
  tasklistItems = list.getItems(camlQuery);
  ctx.load(tasklistItems);
  ctx.executeQueryAsync(OnSuccessGetTaskComments,OnfailGetTaskComments);
}  function OnSuccessGetTaskComments()
 {
  var itemCount = tasklistItems.get_count();
  if(itemCount > 0)
  {
   var divHtml ="<table class='CommentTable '><thead><tr><th>Approvers</th><th>Log</th><th>Comments</th></tr></thead><tbody>";
   var items = tasklistItems.getEnumerator();
   var i=1;   var nextApp; var log; var submitedDate;
 
   while (items.moveNext())
   {
    var listitems = items.get_current();
    var app =  listitems.get_item('AssignedTo').get_lookupValue();
    var outcome = listitems.get_item('WorkflowOutcome');
    var comments =  listitems.get_item('ApproverComments');
    var taskTitle =  listitems.get_item('Title');
    var modifyDate = new Date(listitems.get_item('Modified')).toLocaleString();
    var CreatedDate = new Date(listitems.get_item('Created')).toLocaleString();


 log = "<ul>";
 if(!comments)
   comments ='-';  
   if(i==1)
   {
    requestor = 'Requestor';
 

 if(outcome =='Approve' && taskTitle.indexOf("Request More Information") > -1)
 {
  log = "<li>Submitted to "+app+" for Request more Information by by "+requestor +" on "+CreatedDate+" </li>";
  log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
 }
 else if(outcome =='Approve')
 {
  log = "<li>Submitted to "+app+" for approval by "+requestor +" on "+CreatedDate+" </li>";
  log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
 }

 if(outcome =='Request more Information')
 {
   log = "<li>Submitted to "+app+" for Request more Information by "+requestor +" on "+CreatedDate+" </li>";
   log += "<li>Request more Information by "+app+"  on "+modifyDate+" </li>";
 }
 if(outcome =='Reject')
 {
   log = "<li>Submitted to "+app+" for approval by "+requestor +" on "+CreatedDate+" </li>";
   log += "<li>Rejected by "+app+"  on "+modifyDate+" </li>";
 
    }
    if(outcome =='Pending')
    {
     log = "<li>Submitted to "+app+" for approval by "+requestor +" on "+CreatedDate+" </li>";
    }
    submitedDate = modifyDate;
    nextApp = app;
   }
   else
   {  
 
    if(outcome =='Approve' && taskTitle.indexOf("Review") > -1)
 {
   log = "<li>Submitted to "+app+" for review by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Reviewed by "+app+"  on "+modifyDate+" </li>";
 }
 else if(outcome =='Approve' && taskTitle.indexOf("Request More Information") > -1)
 {
   log = "<li>Submitted to "+app+" for Request More Information by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
 }
    else if(outcome =='Approve')
    {
     log = "<li> Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" </li>";
     log += "<li>Approved by "+app+"  on "+modifyDate+" </li>";
    }

 if(outcome =='Request more Information' && taskTitle.indexOf("Review") > -1)
    {
      log = "<li> Submitted to "+app+" for review by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Request more Information by "+app+"  on "+modifyDate+" </li>";
    }
    else if(outcome =='Request more Information')
    {
      log = "<li> Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" </li>";
      log += "<li>Request more Information by "+app+"  on "+modifyDate+" </li>";
    }
    if(outcome =='Reject')
    {
      log = "<li> Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" </li>";
    log += "<li>Rejected by "+app+"  on "+modifyDate+" </li>";
 }

 if(outcome =='Pending' && taskTitle.indexOf("Review") > -1)
    {
      log = "Submitted to "+app+" for Review by "+nextApp +" on "+submitedDate+" ";
    }
    else if(outcome =='Pending' && taskTitle.indexOf("Request More Information") > -1)
    {
      log = "Submitted to "+app+" for Request More Information by "+nextApp +" on "+submitedDate+" ";
    }
 else if(outcome =='Pending')
 {
    log = "Submitted to "+app+" for approval by "+nextApp +" on "+submitedDate+" ";
 }
 
     log += "</ul>";

     nextApp = app;
     submitedDate = modifyDate;
   }
 
     i = i+1;
 
    divHtml +="<tr><td width='120px'>"+app+"</td><td width='250px'>"+log+"</td><td>"+comments+"</td></tr>";
  }
 
  divHtml +="</tbody></table>";
  var txtArea = NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).html(divHtml);NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).css('overflow-x','hidden');
  NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).css('border','none');
  NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).css('width','100%');
  NWF$('#'+ LogBox).closest('tr').find('div[id$="_inplacerte"]').eq(1).attr("contentEditable","false");
  NWF$('#'+LogBox).prop("readonly", true);

       
 }
} function OnfailGetTaskComments()
 {
 
 }  

 var approveOrReview = "Approve";

 function CheckMsgForLastUserInWF()
 {
  var i = 0; var userMessage; var flag = '0';
  for(i=0 ; i<finalApprovers.length ;i++)
  {
   var currentUserid = _spPageContextInfo.userId;
 
   if(finalApprovers[i].key == currentUserid && finalApprovers[i].value == 'Pending')
   {
    if(finalApprovers[i+1])
    {
  if(finalApprovers[i+1].type == "rev1" || finalApprovers[i+1].type == "rev2")
  {
      if(finalApprovers[i+1].type == "rev2")
   {
       userMessage = "Once you review this new deal, it will be sent to "+finalApprovers[i+1].UName+" for review.  Are you sure you want to continue?";
   }
   else
   {
    userMessage = "Once you approve this new deal, it will be sent to "+finalApprovers[i+1].UName+" for review.  Are you sure you want to continue?";
   }
 
  }
  else
  {
           userMessage = "Once you approve this new deal, it will be sent to "+finalApprovers[i+1].UName+" for approval.  Are you sure you want to continue?";
        }
    }
    else
    {
  if(finalApprovers[i].type == "rev1" || finalApprovers[i].type == "rev2")
  {
    userMessage = "You are about to review this New deal. Are you sure you want to continue?" ;
 
  }
  else
  {
     userMessage = "You are about to approve this New deal. Are you sure you want to continue?" ;
  }
    }
     
    flag = '1';
   }
    if(flag == '0')
   {
     userMessage = "Once you approve this new deal, it will be sent to "+finalApprovers[0].UName+" for approval.  Are you sure you want to continue?";
   }
 
  }
  if(userMessage.indexOf("review") > -1 && userMessage.indexOf("approve") == -1)
  {
   approveOrReview = "review";
  }
  return userMessage;
 }


 function ApproverAction(outcome)
 {
   
    var value = outcome.split('-')[0];
    var result;
 
    if(value =='Approve')
    {
  result = confirm(CheckMsgForLastUserInWF());
 
   if(result)
    {
  try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
 }
    return;
    }
 if(value =='Reject')
    {
     result = confirm("Are you sure you want to Reject New Deal?");
  if(result)
  {
   var value = NWF$('#'+ CommentBox).val();
   if(!value)
   {
    alert("Enter your Remarks before rejecting the New Deal.");
    return;
   }
   else
   {
   try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
   
   }
  }
    }
  if(value =='Request more Information')
    {
      result = confirm("Are you sure you want to Request for More information?");
   if(result)
   {
    var value = NWF$('#'+ CommentBox).val();
    if(!value)
    {
     alert("Enter your Remarks before Requesting More information.");
     return;
    }
    else
    {
   try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
 
 }
   }
 }
 
 }

  var outcomeValue;
  function UpdateTaskList(outcome)
  {
  outcomeValue =  outcome.split('-')[0];
 var outcomeId =  outcome.split('-')[1];
 var comments = NWF$('#'+ CommentBox).val();
 
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(taskListName);
 
    oListItem = oList.getItemById(taskItemId);
    oListItem.set_item('WorkflowOutcome', outcomeValue);
    oListItem.set_item('Completed',true);
    oListItem.set_item('PercentComplete',1);
    oListItem.set_item('Status','Completed');
    oListItem.set_item('FormData','Completed');
    oListItem.set_item('Decision',outcomeId);
    oListItem.set_item('ApproverComments',comments);

    oListItem.update();
 clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryUpdateTaskSucceeded), Function.createDelegate(this, this.onQueryUpdateTaskFailed));
  }
 
function onQueryUpdateTaskSucceeded()
  {
   var isREQ =  NWF$('#' +REQ).val();
   var url = window.location.href;
   if(outcomeValue =="Approve")
   {
    if(approveOrReview == "review")
    {
      alert("New Deal request is Reviewed");  
    }
    else if(isREQ == 'Yes')
    {
     alert('New Deal is sent for Approval');
    }
   else
   {
     alert("New Deal request is Approved");
      window.location.href = window.location;
   }
     
     
   }
   if(outcomeValue =="Reject")
   {
    alert("New Deal request is Rejected");
     
   }
   if(outcomeValue =="Request more Information")
   {
    requestor =  'Requestor';
    alert("New Deal request is sent to "+requestor+" for Request more Information");
 
   }
   
     location.reload(true);

  }
 
  function onQueryUpdateTaskFailed()
  {
    alert("Something went wrong...");
  }
 


 var itemsColl; var currentWeb; var notionvalueGTval; var notionvalueLTval; var isValid;

 function CheckForRequestorNameInAppLimits()
 {
  var context  = new SP.ClientContext.get_current();
  var list     = context.get_web().get_lists().getByTitle(listName);
  var camlQuery = new SP.CamlQuery();
  currentWeb = _spPageContextInfo.webServerRelativeUrl;
 
  camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='TraderID' /><Value Type='Text'>"+_spPageContextInfo.userId+"</Value></Eq></Where></Query></View>");
  itemsColl = list.getItems(camlQuery);
  context.load(itemsColl);
  context.executeQueryAsync(onSuccesCall, OnFailCall);
  }

 function onSuccesCall(sender, args)
 {
  var count = itemsColl.get_count();
 
 if(count > 0)
  {
    var items = itemsColl.getEnumerator();
    while(items.moveNext())
    {
      var notionalValue = NWF$('#'+NotionalVal).val();
      if(notionalValue)
      {
  var listItem = items.get_current();
  notionvalueGTval = listItem.get_item("Notional_x0020_Value_x003e_");
  notionvalueLTval = listItem.get_item("Notional_x0020_Value_x003c__x003");
  var notionalValue = NWF$('#'+NotionalVal).val();
   if(notionalValue >= notionvalueGTval && notionalValue <= notionvalueLTval)
   {
     
    var result = confirm("This New Deal will be submitted  to "+app1+" for approval. Are you sure you want to continue ?");
    if(result)
    {
      try
   {
         SubmitApproval();
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
    }
    else
    {
     return;
    }
   }
   else
   {
      NWF$('.btnSubmitWFCss').eq(1).attr('disabled','disabled');
     alert("Unable to populate approvers for this new deal. Please contact your administrator to ensure that there is an approval limit for this notional value for your approver’s type in the Approver Limits");
   }
        }
     }
  }
  else
  {
   alert('Your are not part of Approval Limits, Contact your administrator/site owner to have your name added to the Approval Limits & Approvers Profile Form.');
   window.location =  ndpListUrl;
  }
  return isValid;
 }
 
 function OnFailCall(sender, args)
 {
  alert("Something went wrong...");
 }



 function SubmitForApproval(outcome)
 {
  var isREQ =  NWF$('#' +REQ).val();
  var IsSubmitForApproval =  NWF$('#' +SubForApproval).val();
  var currentUid = _spPageContextInfo.userId;

   var result = confirm("This New Deal will be submitted  to "+app1+" for approval. Are you sure you want to continue ?");
   if(result)
   {
     if(currentUid == initiatorId && isREQ == 'Yes' && IsSubmitForApproval == 'Yes')
       {
    var value = NWF$('#'+ CommentBox).val();
    if(!value)
    {
          alert("Enter your Remarks before submitting the New Deal.");
          return;
    }
    else
    {
      try
   {
       UpdateTaskList(outcome);
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
    }
  }
  else
   {
      try
   {
         SubmitApproval();
   }
   catch(e)
   {
    alert("Something went wrong...");
   }
   }
   }
   return;
 }  
 
 
 
var modalDialog;

function SubmitApproval()
{
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(ndpList);
    var ID = getParam("ID");
 var notionalValue = NWF$('#'+NotionalVal).val();
 oListItem = oList.getItemById(ID);
 oListItem.set_item('SubmitForApproval','Yes');
 oListItem.set_item('Status','InProgress');
 oListItem.set_item('National_x0020_Value',notionalValue);
 oListItem.update();
  modalDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Submitting New Deal for approval...');
 clientContext.executeQueryAsync(OnSuccessSubmitForApproval,OnFailSubmitForApproval);
}
function OnSuccessSubmitForApproval()
{
 modalDialog.close(0);
 alert('New Deal is sent for Approval');
 window.location = ndpListUrl;

}
function OnFailSubmitForApproval()
{
 RedirectToAllitemsView();
}
    

Get PeoplePicker Value on Nintex form -(Approval Limits)



 var traderList = 'Trader/Approver';var approversList = 'Approval Limits';


 NWF.FormFiller.Events.RegisterAfterReady(function()
{  
   NWF$('.ip-container').eq(0).addClass('ip-container nf-filler-highlightonvalidationerror ip-disabled');
   NWF$('.ip-container').eq(0).attr('style','background-color: #dedede !important; border:none !important;height:28px');
   NWF$('#'+approverType).attr('style', 'background-color: #dedede !important; border:none !important;width:458px;height:28px');
   NWF$('#'+approverType).prop("readonly", true);     NWF$('#'+traderDdl).change(function()
    {
     var id = NWF$('#'+traderDdl).val().split(';')[0];
             GetManagerOfTrader(id);
     });

});
var items;
function GetManagerOfTrader(Id)
{
  var ctx = new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle(traderList);
  var camlQuery = new SP.CamlQuery();
  var query = "<View><Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>"+Id+"</Value></Eq></Where></Query></View>";
 
  camlQuery.set_viewXml(query);
  items = list.getItems(camlQuery);
  ctx.load(items);
  ctx.executeQueryAsync(OnSuccess,Onfail);
}
function OnSuccess()
{
 var count = items.get_count();
 if(count > 0)
 {
  var listItems = items.getEnumerator();
  while(listItems.moveNext())
  {
    var item = listItems.get_current();
    var managerName = item.get_item("Approver").get_lookupValue();
    var managerId = item.get_item("Approver").get_lookupId();
   // var approvertype = item.get_item("ApproverTypeLabel");
 var managerId = item.get_item("Approver").get_lookupId();

 var traderId = item.get_item("Trader").get_lookupId();
 var AppType = item.get_item("Approver_x0020_Type").get_lookupValue();
 
      //  NWF$('#'+FirstApprover).prop("readonly", true);
    var approverPicker = new NF.PeoplePickerApi('#' + FirstApprover);
 
 approverPicker.clear();

// RemoveOtherAppInApp1Field();
    var waitscreen = SP.UI.ModalDialog.showWaitScreenWithNoClose('Working on it...');
    approverPicker.search(managerName).done(function (data) {
                //add line manager to people picker field
    approverPicker.clear();
                approverPicker.add(data[0]);
                waitscreen.close(0);
                NWF$('.ip-item span div').eq(1).removeClass('ip-close');
             
             });
 
    NWF$('#'+approverType).val(AppType);      NWF$('#'+traderIdtext).val(traderId);

  }
 }
}
function Onfail()
{}


 function RemoveOtherAppInApp1Field()
 {
 var len = NWF$('.ip-disabled div.ip-item').length;
 if(len > 0)
 {
  for(var i=0;i<len;i++)
  {
   NWF$('.ip-disabled div.ip-item').eq(i).remove();
  }
 }
 }

Call the Service from JQuery

Call the Service from JQuery

The following demonstrates how to call the service from a Script Editor Web Part using simple HTML, JavaScript and JQuery.
source: Source
  1. <script src="http://sp13.dev/SiteAssets/jquery-1.10.2.min.js"></script>
    
    <h2>SharePoint 2013: Consume a custom WCF REST service hosted in SharePoint 2013.</h2>
    <h3>This is a quick sample to demonstrate calling a custom SharePoint-hosted WCF REST service from a
        Script Editor Web Part using simple HTML, JavaScript and JQuery.
    </h3>
    
    <div>
        <br />
        <p id="message">Loading presidents...</p>
    </div>
    
    <div id="resultsPanel"></div>
    
    <script type="text/javascript">
        $(document).ready(function () {
            getPresidentsData();
        });
      
    function getPresidentsData() {
        var serviceUri = _spPageContextInfo.webAbsoluteUrl +
            "/_vti_bin/BarkesServices/PresidentsService.svc/GetAllPresidents";
        $.ajax({
            type: "GET",
            contentType: "application/json",
            url: serviceUri,
            dataType: "json",
            success:
                function (response) {
                    showPresidentsList(response);
                    $('#message').html("<a href=" + serviceUri + ">" + serviceUri + "</a>");
                },
            error:
                function (err) {
                    alert(err);
                }
        });
    }
    
    function showPresidentsList(presidentsData) {
        $.each(presidentsData, function () {
            $('#resultsPanel').append($(this)[0].Id + ' - ');
            $('#resultsPanel').append($(this)[0].FirstName + ' ');
            $('#resultsPanel').append($(this)[0].LastName + ' (');
            $('#resultsPanel').append($(this)[0].EmailAddress + ')');
            $('#resultsPanel').append('<br><br>');
        });
    }
    </script>