5

I am setting a viewScope variable in a server side javascript (SSJS) button.

viewScope.put("branchName",doc.getItemValueString("BranchName"))

How can I access that variable on the client side?

infused
  • 24,000
  • 13
  • 68
  • 78
Bruce Stemplewski
  • 1,343
  • 1
  • 23
  • 66

5 Answers5

14

If you need to access the viewScope variable from a client side script you can use the xp:scriptBlock tag to setup a number of global javascript variables.

<xp:scriptBlock id="scriptBlock1">
<xp:this.value><![CDATA[var myVar = #{javascript:viewScope.get("scopeVar")}]]></xp:this.value>
</xp:scriptBlock>

The main problem with this method is that the inner server side javascript is only computed when that element is initially rendered or when a partial refresh is performed on the element so there is no guarantee that the client side JS variable is set to the correct value.

Declan Lynch
  • 3,345
  • 17
  • 36
8

You can't access viewScope Variables directly, but you could bind it to a hidden field then access that value via csjs XSP.getElementById("#{id:inputHidden1}").value

There are other ways to access it also, using something like rpc or an ajax request.

Toby Samples
  • 2,168
  • 14
  • 15
6

use the below code:

var value = "#{javascript:viewScope.variablename}"
NotesArt
  • 383
  • 9
  • 20
5

I would take a look at the JSON RPC included with the extension library. This component will allow you to define a SSJS function that may/may not accept arguments. Let's say you add the RPC with an ID of myRPC and a method called getViewScopeVar that accepts a single String argument and returns the value of the viewScope variable with the name that you include as the argument. You can then call that method like:

myRPC.getViewScopeVar("branchName")

This is the easiest most effective way to interact with server side elements from client side javascript. Plus it gives you the option of all the required methods being in one place as long as you place that RPC on a strategic custom control (i.e. like a layout custom control that every xpage is based off of).

keithstric
  • 1,053
  • 1
  • 11
  • 21
0

If you need frequent updates you can use the Ajax service from the extension library.

stwissel
  • 20,110
  • 6
  • 54
  • 101