How can i access velocity variable in java script

{{velocity}}
#set( $foo = $xwiki.getUserName(“XWiki.$xcontext.getUser()”,false))
Hello $foo World!
$xcontext.put(“name”, $foo)
{{/velocity}}

###/script type=“text/javascript”>
var myvar = “${name}”;
alert ($name);
</script
/

I need username for verification purpose. I am unable to fetch username in javascript. Please help me out with this.

You have 3 options:

  1. Write the Velocity code inside the JavaScript code and configure the JavaScript code to be evaluated on the server side. This way the Velocity code is executed on the server side before the JavaScript code is returned to the browser.
  2. Store the value of the Velocity variable in an HTML attribute (don’t forget to use XML encoding) and then read the value of that attribute from the JavaScript code
  3. Make an AJAX request from JavaScript to a server-side Velocity script that computes and returns the value.

Hope this helps,
Marius

I think we should also improve XWiki and make the currently logged in user available along with the other document-related data we provide: http://www.xwiki.org/xwiki/bin/view/Documentation/DevGuide/FrontendResources/JavaScriptAPI/#HGetsomeinformationaboutthecurrentdocument

@mflorea Would that be a good idea? I see often people asking how to get the current user from JS.

Of course.