SharePoint JSLink (Client Side Rendering)

// List New and Edit Forms  – HTML5  Input Sample

(function () {

    // Create object that have the context information about the field that we want to change it’s output render

var ageFiledContext = {};

ageFiledContext.Templates = {};

ageFieldContext.Templates.OnPreRender = onPreRender;

ageFiledContext.Templates.OnPostRender = onPostRender;

ageFiledContext.Templates.Fields = {

        // Apply the new rendering for Age field on New and Edit forms, Using InternalName

“Age”: {             “NewForm“: ageFiledTemplate        }

};

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ageFiledContext);

})();

// This function provides the rendering logic

function ageFiledTemplate(ctx) {

var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

        // Register a callback just before submit.   IMPORTANT to ensure the field would still work when user save/update

formCtx.registerGetValueCallback(formCtx.fieldName, function () {

return document.getElementById(‘inpAge’).value;

});

var testValue = “ABC”;

return “<input type=’text’ id=’inpAge’ min=’18’ max=’110′ value='” + testValue + “‘/>”;

}
function onPostRender(ctx) {
}
function onPreRender(ctx) {
}

Advertisements

SharePoint 2013 – Get Current User LoginName using JSOM & REST

Using SharePoint 2013 REST Service

$(document).ready(function () {

var userid = _spPageContextInfo.userId;

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : onSuccess,
  error : onError
});
}

function onSuccess(data, request){
  var loginName = data.d.LoginName.split('|')[1];
  alert(loginName);
}

function onError(error) {
  alert(error);
}

GetCurrentUser();

});

Using SharePoint 2013 JSOM

$(document).ready(function () { 

var currentUser;
// Ensure that the SP.js is loaded
if (SP.ClientContext != null) {
  SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');
}
else {
  SP.SOD.executeFunc('sp.js', null, getCurrentUser);
}

function getCurrentUser() {
  var context = new SP.ClientContext.get_current();
  var web = context.get_web();
  currentUser = web.get_currentUser();
  context.load(currentUser);
  context.executeQueryAsync(onSuccessMethod, onRequestFail);
}

function onSuccessMethod(sender, args) {
  var account = currentUser.get_loginName();
  var currentUserAccount = account.substring(account.indexOf("|") + 1);
  alert(currentUserAccount);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
  alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
}

});

Conclusion: 

I would suggest using REST since it does not require SP.js to be loaded.

SP.js is only loaded on demand in some pages.

Inject Tag for Label element by JQuery

Jquery doesn’t work well with for attribute of <label>, $(‘label[for=”reporter”]’) will null.


var OnlyForCreateRecord = function() {
var pageText = $('h2.aui-popup-heading').text();
if (pageText.indexOf("Create Record") >= 0) {
var InsertAsterisk = function() {
var fieldNames = [ 'issuetype', 'reporter', 'summary', 'customfield_10200' ];


for (var index in fieldNames)
{ // return the first sibling label element
var requiredLabel = $("[name*='" + fieldNames[index] + "']").siblings('label').first();
if ($(requiredLabel).children('span').length <= 0)
{
$(requiredLabel).append("<span class='aui-icon icon-required' />");
//alert("Injecting Validation for Field: " + fieldNames[index]);
}
}
};

// since the fields are rendered by javascript also, make sure the fields have been presented.
setTimeout(InsertAsterisk, 500);
}
}
setTimeout(OnlyForCreateRecord, 250);

Check broken link of in server side and client side

Server side using C# code:

NOTE: using System.Net;

Uri urlCheck = new Uri("http://dev.test.com/_layouts/images/test_img.jpg");
HttpWebReqeust request = (HttpWebRequest)WebRequest.Create(urlCheck);
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;

try
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    imgTag.ImageUrl = "http://dev.test.com/_layouts/images/test_img.jpg";
}
catch(Exception)
{
    imgTag.ImageUrl = "/_layouts/images/error_img.png";
}

Client side using JQuery:

$(document).ready(function() {
     $("img[id=imgUserPhoto]").error(function() {
          $(this).attr("src", "/_layouts/images/error_img.png");
     });
});

JQuery Notes 1


$(document).ready(function () {
   // Get URL and convert to lower case
   var urlStringInLowerCase = document.location.href.toLowerCase();
   if (urlStringInLowerCase.indexOf('/fr/') >= 0)
   {
      $('#ctl00_IdWelcome_ExplicitLogout_ctl00_ctl01').attr('text', 'English');
      $('#ctl00_IdWelcome_ExplicitLogout_ctl00_ctl01').attr('onMenuClick', "window.location='javascript:ChangeLang(1033);';");
   }
   else
   {
      $('#ctl00_IdWelcome_ExplicitLogout_ctl00_ctl01').attr('text', vlang);
      $('#ctl00_IdWelcome_ExplicitLogout_ctl00_ctl01').attr('onMenuClick', "window.location='javascript:ChangeLang(1036);';");
   }


   // Hide Menu Item - My Setting
   var menu = document.getElementsByTagName('ie:menuitem');
   for (var i = 0; i < menu.length; i++) { 
       var itm = menu[i];
      // Regular Expression
      var rex = /(.)*?PersonalInformation$/;
      if (itm.id.match(rex))
      { itm.hidden = true; }
   }
   //code to vanish the search string when clicked on search box
   var searchBox = $(document).find(':input[name$="InputKeywords"]');
   var prompt = ""; searchBox.addClass("cibc-sb");
   if (urlStringInLowerCase.indexOf('/fr/') >= 0) {
      prompt = "Chercher une personne";
   }
   else {
       prompt = "Search people";
   }
   searchBox.attr("value", prompt);
   searchBox.focus(function () {
      $(this).removeClass("cibc-sb");
      ($(this).attr("value") == prompt) ? $(this).attr("value", "") : 0;
   }).blur(function () {
      ($(this).attr("value") == "") ? $(this).attr("value", prompt).addClass("cibc-sb") : 0;
   });
});


function ChangeLang(value) {
var url = window.location.href.toLowerCase();
var today = new Date();
var oneYear = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
// Set Cookie
document.cookie = "lcid=" + value + ";path=/;expires=" + oneYear.toGMTString();
if (value == "1033") {
window.location.href = url.replace('/fr/', '/en/');
}
else {
window.location.href = url.replace('/en/', '/fr/');
}
}

AJAX 学习笔记 – 1

AJAX 学习笔记 – 1

AJAX

XMLHttpRequest 对象

所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。

XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

var xmlhttp; 
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari 
 xmlhttp=new XMLHttpRequest(); 
} 
else {
// code for IE6, IE5 
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
}

XMLHttpRequest 对象用于和服务器交换数据。如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
方法 描述
open(method,url,async) 规定请求的类型、URL 以及是否异步处理请求。

  • method:请求的类型;GET 或 POST
  • url:文件在服务器上的位置
  • async:true(异步)或 false(同步)
send(string) 将请求发送到服务器。

  • string:仅用于 POST 请求

AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。

XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true。

当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","test1.txt",true); xmlhttp.send(); 

GET 请求


一个简单的 GET 请求:

xmlhttp.open("GET","demo_get.asp",true); xmlhttp.send();

在上面的例子中,您可能得到的是缓存的结果。

为了避免这种情况,请向 URL 添加一个唯一的 ID:

xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true); xmlhttp.send();

如果您希望通过 GET 方法发送信息,请向 URL 添加信息:

xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true); xmlhttp.send();

一个简单 POST 请求:

xmlhttp.open("POST","demo_post.asp",true); xmlhttp.send();

如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:

xmlhttp.open("POST","ajax_test.asp",true); 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send("fname=Bill&lname=Gates"); 

服务器响应


如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。


属性 描述
responseText 获得字符串形式的响应数据。
responseXML 获得 XML 形式的响应数据。

下面是 XMLHttpRequest 对象的三个重要的属性:


属性 描述
onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

  • 0: 请求未初始化(request not initialized)
  • 1: 服务器连接已建立(server connection established)
  • 2: 请求已接收(request received )
  • 3: 请求处理中(processing request )
  • 4: 请求已完成,且响应已就绪(request finished and response is ready)
status 200: “OK”

404: 未找到页面


当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

 
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }