Passing data from a Roxy app to a JavaScript widget…

This is a quick post to show how to pass information in to a JavaScript widget from a Roxy application…

There are times when you need to pass application information in to your JavaScript code. The easiest way to do this is on your XQuery view.

In the example below we’re going to alter our previous chart search example to include the user’s username in the name of their search options. This keeps search options from bumping in to each other between users of the same system.

Firstly, you need a page scope variable in JavaScript. You do this by adding the following code at line 35 of your chartsearch.html.xqy file:-

<script type=”text/javascript”>var userid=”{xdmp:current-user()}”;</script>

The { and } code gets the current logged in username from MarkLogic and places it in the value for userid. Note the “” are important.

Now alter your page-chartsearch.js file so that line 6 now reads:-

var optionsName = userid + “-page-charts-search”;

The prepends your username and a ‘-‘ to the search options name.

Now deploy using:-

./ml local deploy modules

Now visit http://yourserver:port/mldbtest/chartsearch.html

You will see the page works exactly the same as before. If you read your JavaScript console, though, you’ll notice the search options have been saved to MarkLogic with the new name.

Conclusion

You can use this method to pass any information to your JavaScript. You can even pass in raw JSON by using the same approach as above, but without the ” ” characters – all XQuery functions are executes before content is sent to the browser, just like ye olde server side includes or JSP code, so the client just sees the raw results within the JavaScript block.

A typical use case would be for information on the ‘current user’ which is usually beyond what MLDB can see when it executes within the browser. Other use cases may be for server side generated context information, such as the user’s current roles, or JSON search result configuration. You could even bypass MLDB’s search widgets and visualise any XQuery rendered results directly as JSON using the search results widget.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s