Help to read current user name and domain in sharepoint by javascript

Hello Experts,
 We have created the web service to check the user is belongs to Active Directory or not for our Access Denied Page. Now we have to use Rest Api to use the method. The web service has three parameters 1. Security Group 2. Username 3. Domain.

I will need to pass current user name and domain to this web service. This method return Boolean.  Based on value i have to display different html. I may have to use SPcontext to read current username and domain.

Function call()
{
setData="{'SecurityGroup':'','UserName':'','domainName':''}";
    $.ajax({
        type: "POST",
        url: _spPageContextInfo.webAbsoluteUrl+"/_layouts/15/FindUserSecGroupMembership/CheckUserADMembership.aspx/IsMemberOf",
       data:setData,
        async: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
                                                //debugger;
               //if(data.d.length>0){
                console.log(data)
           //}
                },
        error: function (error) {debugger;
            console.log(JSON.stringify(error));
        }
    });
}

Open in new window


Can you please help me to write code to pass username and domain and display html based on output?
sharepoint0520Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Your JSON is wrong - JSON requires double quotes i.e.
var setData='{"SecurityGroup":"","UserName":"","domainName":""}';

Open in new window

However instead of doing this rather do this
var setData={
  SecurityGroup: "",
  UserName:"",
  domainName:""
};

Open in new window

And then in your $.ajax call
$.ajax({
  url: url: _spPageContextInfo.webAbsoluteUrl+"/_layouts/15/FindUserSecGroupMembership/CheckUserADMembership.aspx/IsMemberOf",
  data: JSON.stringify(setData),
  contentType: 'application/json; charset=utf-8',
  type: 'POST',
  /* async: false,  <======== WHY ARE YOU DOING THIS? THIS IS A BAD PRACTICE? */
}).then(function(resp) {
   console.log(resp); // <========= WHAT DOES THIS LOOK LIKE
});

Open in new window

If you are using jQuery < 1.8 then you will have to use the success attribute for the callback instead of .then() as I have used above.

Let's look at what your data coming back looks like and then we can discuss what to do with it.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sharepoint0520Author Commented:
Julian,
 Thanks for you comment. Exactly we just created the web method to identify current user in Active Directory or not. If user in AD then i need to display pop that user in AD. I am trying to use Rest API to access that web method. It has three parameters.  But still my code is incomplete and  not working. Can you please review my full code and help me to rewrite?

<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script src="https://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript" ></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 group = "AD Group";
    var loginName = data.d.LoginName;
    var input = loginName;
    var x = input.match(/[^|]*\|([^\\]*)\\(.*)/)
    var user = x[2];
    var domain = x[1];

    var setData = { 'migratedSecurityGroup':group, 'User':user, 'domain': domain };
    $.ajax({
        type: "POST",
        url: _spPageContextInfo.webAbsoluteUrl+"/_layouts/15/FindUserSecGroupMembership/CheckUserADMembership.aspx/IsMemberOf",
        data: JSON.stringify(setData),
        async: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            //debugger;
            //if(data.d.length>0){
            console.log(data)
            alert(data);
            //}
        },
        error: function (error) {debugger;
            console.log(JSON.stringify(error));
        }
    });

}

function onError(error) {
    alert("error");
}</script>

Open in new window

Julian HansenCommented:
Can you expand on "Not Working"

If you look at the POST request in the Console (F12)
- Look for the POST http:// .....
- Click on this to expand it
- Click the parameters tab  - what is shown there?
- Click the response tab - what is shown there

Any errors in the console?
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Julian HansenCommented:
I am confused - you have opened another question here https://www.experts-exchange.com/members/sharepoint0520.html that seems to be a duplicate of the one we are still dealing with.

Is this the case?
sharepoint0520Author Commented:
Hi,
  I have opened the question because i did not get the response at first place and requirement changed . I am still having problem. It throw error  "{"readyState":4,"responseText":"{\"Message\":\"There was an error processing the request.\",\"StackTrace\":\"\",\"ExceptionType\":\"\"}","responseJSON":{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""},"status":500,"statusText":"Internal Server Error"}"

If i remove Var and Jason code then it's work in browser.
Browser_Result.PNG
sharepoint0520Author Commented:
Hi,
 Thank you for your help earlier for Json suggestion. it helped me to fox my code.

<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script src="https://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript" ></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 group = "PAGORG_Farmers_Sharepoint_Migrated";
    var loginName = data.d.LoginName;
    var input = loginName;
    var x = input.match(/[^|]*\|([^\\]*)\\(.*)/)
    var user = x[2];
    var domain = x[1];
   var setData={
       migratedSecurityGroup: "AD Group",
       samAccountName:user,
       domainName:domain
};
 
    $.ajax({
        type: "POST",
        url: _spPageContextInfo.webAbsoluteUrl+"/_layouts/15/FindUserSecGroupMembership/CheckUserADMembership.aspx/IsMemberOf",
       data: JSON.stringify(setData),
        async: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            //debugger;
            if(data.d.length>0){
            console.log(data.d)
            alert(data.d);
           }
        },
        error: function (error) {debugger;
            console.log(JSON.stringify(error));
        }
    });

}

function onError(error) {
    alert("error");
}</script>

Open in new window

Julian HansenCommented:
because i did not get the response
You did get a response - I have been responding to you.
Opening multiple questions is not a good practice
- If your question is not being answered then report it and ask a Mod to notify more experts
- If the requirement changes - close the question - give reasons and point to the new question so that any experts in the current thread
  a) Know there is another thread
  b) You get your answers in one place.

If this question is different from your other one then please explain the difference so we don't overlap.
If it is not then close this question and post link to new question.

As things stand - I don't know where we are with this issue - so I cannot provide further feedback until the above is resolved.
sharepoint0520Author Commented:
Julian,
 Thank you for your suggestion. Next time i will keep in my mind. Thanks for your time and help.
Julian HansenCommented:
You are welcome.

Comments above were intended to help you get the best out of EE - not as criticism (I am not sure if that came across correctly).
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SharePoint

From novice to tech pro — start learning today.