Populate Current User Details in SharePoint InfoPath form using JavaScript

This SharePoint JSOM tutorial will discuss how to populate current user details in the SharePoint InfoPath form using the JavaScript object model.

Recently I got a requirement where we need to populate the current user details like name, email address, etc using JavaScript client object model.

So what I did is Edit the NewForm (newifs.aspx) page, and add a script editor web part and add the below code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(getUserDetails, "SP.js");

var user;
var email;
var firstname;
var surname;

function getUserDetails()
{
var clientContext = new SP.ClientContext();
user = clientContext.get_web().get_currentUser();
clientContext.load(user);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded() {
var UserName = user.get_title();
var UserNamearray = UserName.split(" ");
firstname= UserNamearray[0];
surname= UserNamearray[1];
email = user.get_email();

var fname= document.getElementById("ctl00_ctl39_g_963a8e7b_4a40_47b3_b19d_75e8788355a7_FormControl0_V1_I1_T3").value=firstname;
document.getElementById("ctl00_ctl39_g_963a8e7b_4a40_47b3_b19d_75e8788355a7_FormControl0_V1_I1_T3").focus();

var sname= document.getElementById("ctl00_ctl39_g_963a8e7b_4a40_47b3_b19d_75e8788355a7_FormControl0_V1_I1_T4").value=surname;
document.getElementById("ctl00_ctl39_g_963a8e7b_4a40_47b3_b19d_75e8788355a7_FormControl0_V1_I1_T4").focus();

var emailid=document.getElementById("ctl00_ctl39_g_963a8e7b_4a40_47b3_b19d_75e8788355a7_FormControl0_V1_I1_T5").value=email;
document.getElementById("ctl00_ctl39_g_963a8e7b_4a40_47b3_b19d_75e8788355a7_FormControl0_V1_I1_T5").focus();
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Now it should populate like below:

Get Current User Details in SharePoint InfoPath form using JavaScript

If the value did not preserve, you can go to the InfoPath textbox properties and then select “None” in Browsers forms tab like below:

Populate Current User Details in SharePoint InfoPath form using JavaScript

You may like following SharePoint InfoPath tutorials:

Here, we learned how to populate Current User Details in the SharePoint InfoPath form using the JavaScript Object model.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>