1

I am working on sharepoint online. I am trying to display my current sharepoint username using script and i am able to display it. While my page is loading the content is shown but as soon as its gets loaded the content in my body disappears and a blank white page with the current username gets shown. I already searched net it tells to close your script tags properly and i checked they are already closed properly.

The script is in my header tag

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script>

$(document).ready(function(){
    var scriptbase = "https://MySiteUrl" + "/_layouts/15/";

 $.getScript(scriptbase + "init.js",
        function () {
            $.getScript(scriptbase + "SP.Runtime.js",
               function () {
            $.getScript(scriptbase + "SP.js", GetLoginName);
          });
      });
       });


function GetLoginName()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();  
var currentUser = web.get_currentUser();  
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(
  function(){ //On success function
    var userObject = web.get_currentUser();
    var loginName = userObject.get_title();
    document.write(loginName);

 },
 function(){ //On fail function
    alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
 }
 );
}
</script>

In my body right now i am simply displaying hello which disappears.

<body>
<form id="form1" runat="server">
    <div>hello</div>        
</form> 
</body>

I tried my script in all the places such as in head, in body, at the end but nothing works. What am i doing wrong ?

1
  • Don't use document.write, add a new node in the DOM instead Nov 2, 2017 at 6:43

2 Answers 2

2

document.write

That method will overwrite the whole content of your page. Uses instead a selector to target your HTML node:

document.querySelector("selector").innerText = "Hello "+logonName:

Or by jQuery:

$("selector").text("Hello "+logonName);

-1

Instead of

document.write    

use

document.getElementById("usershow").innerHTML = loginName;

<body>
<form runat="server">
    <div>hello</div>
    <div id="usershow">user<div>
</form>

</body>
1
  • Hi @andy , Is the above answer is not solved your issue? he provides you the key solution so why you don't accept it? Nov 2, 2017 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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