Updating the XWiki UI using a bit of JavaScript and Velocity code

Last modified by Oana Florea on 2020/01/28

Jul 14 2016

It's natural that depending on the actions of users, we want to also update the UI. For example the click of a button, the selection of a checkbox or the scroll of a page. These tasks can be easily achieved using the XWiki platform and some basic web technologies know-how.
Let's say we would like to update the page when the user clicks on a button. The application could have the following architecture:

  • We add a JavaScript extension which contains an AJAX request executed when the user clicks on the button (this step could also extract and pass the parameters to the URL executed with AJAX).
  • The URL executed with AJAX is actually a Velocity page which reads the parameters from the request and calls the proper methods (e.g. we can execute a query, build a JSON or send an email).
  • We update the UI after the request is successfully executed.

To display a button we just need to use the HTML input tag on new page (e.g. TestPage.WebHome):

{{html}}
<input type="submit" name="ajaxButton" id="ajaxButton" value="Call AJAX"/>
<div id="result"></div>
{{/html}}

We also added an extra div element to update it if the request is done successfully.

The next step would be to edit the page in "Objects" mode (requires "advanced" user type to be enabled in your user profile) and add a new (XWiki.)JavaScriptExtension object with the following code:

require(['jquery'], function($) {
  $(document).ready(function(){
    $("#ajaxButton").click(function(e){
      e.preventDefault();
     // Using the core $.ajax() method
     $.ajax({
     
     // The URL for the request
     url: "$xwiki.getURL('TestVelocity.WebHome', 'get', 'xpage=plain&outputSyntax=plain')",
     
     // The data to send (will be converted to a query string)
     data: {
        myvalue: $("#ajaxButton").val()
      },

      success:function(result){
        $("#result").html(result);
      }
      });//ajax
   });//click
 });//ready
});//require

It's important to set the "Parse content" property to "True" for the JavaScriptExtension object since we want to use the velocity API to generate the AJAX request URL (hardcoding URLs is not a good practice because it could cause issues when switching to short URLs or DNS updates).

The AJAX call is done towards the page TestVelocity.WebHome so the last step would be to create one with just a simple check:

{{velocity}}
#if("$!request.myvalue" != '')
Hello World!
#end
{{/velocity}}

Finally, the result when clicking on the button should be the following:

More information can be found by checking the following resources:

Another example which contains advanced best practices: http://extensions.xwiki.org/xwiki/bin/view/Extension/AJAX+example

The code was done on XWiki 8.1, but it should work just as well on older versions.

Tags:
    

Get Connected