Tuesday, 30 December 2014

Get UserInformation/ Site Information Using client side script

Recently I have to display client info on a page. I have two options, either with webpart (server side control) or  use script editor webpart (client object modal).

Here is the script i use:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
  var userid= _spPageContextInfo.userId;
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 Logg = data.d;    
document.getElementById('welcomediv').innerHTML="Hello, "+Logg.Title;
document.getElementsByTagName('title')[0].innerHTML='Home';  
}
function onError(error) {
    alert("error");
}
</script>


If you want Site Name, Here is the code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () { SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getWebProperties); $('.userprofilpic').hide();});
    function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
       ctx.load(this.web,'Title');
        ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));
    }
    function onSuccess(sender, args) {
document.getElementById('welcomediv').innerHTML="Site Name: "+this.web.get_title();    
    }
    function onFail(sender, args) {
        alert('failed to get list. Error:'+args.get_message());
    }
</script>

That's it for now.

No comments:

Post a Comment