Using _spPageContextInfo, AJAX and SAMAccountName to show a hidden item in a SharePoint page.

I wanted to have a link on a page (could be anything) show only for certain people. I knew there was variable on every page named _spPageContextInfo.userId, which is the current user’s SharePoint user Id. I used the following code to take that userId and query the User Information List to get the SAMAccountName, and then use jQuery to show a hidden link if the use name matches.

    var userId = _spPageContextInfo.userId;
    var SAMAccountName = ''
    var serverUrl = "/_vti_bin/listdata.svc/UserInformationList(" + userId + ")"

    var URL = serverUrl
    $.ajax({
        type: "GET",
        contentType: "application/json",
        datatype: "json",
        async: false,
        url: URL,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("Content-Type", "application/json")
        },
        success: function (data, textStatus, XmlHttpRequest) {
            SAMAccountName = data.d.UserName
        }
    });
    if (SAMAccountName.toLowerCase() === 'UserName1'
        || SAMAccountName.toLowerCase() === 'UserName2'
        || SAMAccountName.toLowerCase() === 'UserName3'
        || SAMAccountName.toLowerCase() === 'UserName4'
        ) {
        $('#HiddenId').show()
    }

,

Comments are closed.