0

I want to create a form which allows users to search for a particular user who may not exist on the current site. I can do that using the SearchPrincipals web service, but the users will have an ID of -1 so I can't use that ID in order to set a people picker field in the background. Is there any way that we can add a user to the current site by his/her account name?

1 Answer 1

2

You can use the EnsureUser method of Web object by referring this article. Here is the sample code which will check if the user exists (and return the SPUser object), if it doesn't, it will add the user and then return the SPUser object in JSON:

$.ajax({
    url: "http://<site url>/_api/web/ensureuser ",
    type: "POST",
    data: "{ 'logonName': 'i:0#.f|membership|[email protected]' }",
    headers: {
        "X-RequestDigest": < form digest value > ,
        "content-type": "application/json;odata=verbose"
        "accept": "application/json;odata=verbose"
    },
    success: successHandler,
    error: errorHandler
});
4
  • It seems to be giving different results when I added the content-type underneath the accept header. Fingers crossed..
    – Dinerdo
    Feb 24, 2016 at 4:19
  • I'm having success when using this to search by a specific display name, email address, or account name. I wish there was a way to return a list of users like you have when you use SearchPrincipals. I could link the two together to provide a list since my organization has many users with the same display name, but they should all be able to search by email so that's more than acceptable. Can you add the content-type information to your answer so I can accept it?
    – Dinerdo
    Feb 24, 2016 at 5:11
  • Added content-type header as it is required for the server to identify the type of data being sent along with the POST request. Please accept the answer if it satisfies your requirement.
    – AmitWiki
    Mar 16, 2016 at 19:26
  • Very much appreciated
    – Dinerdo
    Mar 16, 2016 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.