How to Call a Servoy Method from Browser-Side JavaScript (generateBrowserFunction) or Pass Calculated Values Back to Servoy?

Hi all,

I’m working with ChartJS and would appreciate some guidance on passing calculated values from client-side JavaScript back to Servoy.

I have a ChartJS chart where I draw custom flag markers using the sample_flag(chart) method. This method runs in the browser because setChart() passes its code to clientutils.generateBrowserFunction().

The X and Y coordinates of the flags are calculated on the client side using the ChartJS canvas. I need to pass these calculated positions back to Servoy so I can use them for further processing.

What is the recommended way to pass values calculated in browser-side JavaScript back to Servoy? Alternatively, is there a way to call a Servoy form method directly from browser-side JavaScript?

Is there a supported mechanism for invoking a Servoy method from JavaScript generated by clientutils.generateBrowserFunction(), or would another approach be more appropriate?

I would appreciate any guidance or examples of how to implement this.

Environment:

  • Servoy version: 2024.3.9

  • ChartJS version: 2024.3.5

Thanks,
Aijaz Ali

Hi Aijaz,

clientutils.generateBrowserFunction() is one-way. It turns your function string into a function that runs in the browser (the ChartJS docs use it for things like tooltip label callbacks), but it doesn’t give that function a way to call a Servoy method or return values to the server.

The ChartJS component exposes two events of its own:

  • onClick(dataset_index, index, label, value, event): fires when a chart element is clicked.
  • onChartDrawn(): fires when the chart has finished drawing (no parameters).

Neither one carries custom values calculated in the browser. Which route works depends on what the coordinates are for:

  1. If the flags are tied to data points, use onClick. It gives you the dataset index, point index, label and value, so you can work out what you need on the Servoy side from those.
  2. If you need to know when the chart is ready, use onChartDrawn as the trigger. Note that it passes no coordinates.
  3. If the flag positions come from your data rather than from pixel positions, calculate them in Servoy from the same dataset you pass to setData(), and send the result back to the chart as part of the data or options.

There is no supported way to get raw pixel X/Y values calculated in the browser back to a form method with the current component. If you need the pixel values themselves, tell us what you’re doing with them. That would help us suggest a better route.

1 Like

Hi Sean,

Thank you for your response; I appreciate it. I was able to achieve what I needed with a workaround, and I wanted to share it in case it helps others facing a similar issue.

The idea: the browser function can’t call Servoy directly, but it can drive Servoy’s own elements. I put a hidden field and a hidden button on the form. When a flag is clicked, the browser code writes the value into the field and clicks the button, and the button’s normal onAction runs on the server.

  1. On the form, add a text field bound to a form variable (fv_flagId) and a button with onAction set to my method. Give them the style classes flag-bridge-input and flag-bridge-btn, plus a class that hides them with CSS (display: none). Keep visible = true, because invisible elements aren’t rendered in the DOM.

  2. In setOptions, configure the onClick browser function as follows:

onClick: clientutils.generateBrowserFunction(
    "function(evt, elements, chart) {" +
    "  var rect = chart.canvas.getBoundingClientRect();" +
    "  var x = (evt.native ? evt.native.clientX : evt.x) - rect.left;" +
    "  var y = (evt.native ? evt.native.clientY : evt.y) - rect.top;" +
    "  var areas = chart._flagHitAreas || [];" +
    "  for (var i = areas.length - 1; i >= 0; i--) {" +
    "    var a = areas[i];" +
         // Hit only if the click is inside the flag box
    "    if (x >= a.x && x <= a.x + a.w && y >= a.y && y <= a.y + a.h) {" +
         // Find the hidden bridge field and button by their style classes (flag-bridge-input / flag-bridge-btn).
    "      var root = chart.canvas, inpHost = null, btnHost = null;" +
    "      while (root && (!inpHost || !btnHost)) {" +
    "        root = root.parentElement;" +
    "        if (root) {" +
    "          inpHost = root.querySelector('.flag-bridge-input');" +
    "          btnHost = root.querySelector('.flag-bridge-btn');" +
    "        }" +
    "      }" +
           // The class can sit on a wrapper, so look for the real input / button inside it
    "      var inp = inpHost && (inpHost.tagName === 'INPUT' ? inpHost : inpHost.querySelector('input'));" +
    "      var btn = btnHost && (btnHost.tagName === 'BUTTON' ? btnHost : (btnHost.querySelector('button') || btnHost));" +
    "      if (inp && btn) {" +
		     // Put the flag_id in the hidden field and fire the events Servoy listens to,
		     // so the value is sent to the server and stored in fv_flagId
    "        inp.value = a.flag.flag_id;" +
    "        inp.dispatchEvent(new Event('input', {bubbles: true}));" +
    "        inp.dispatchEvent(new Event('change', {bubbles: true}));" +
    "        inp.dispatchEvent(new Event('blur', {bubbles: true}));" +
             // Small delay so the field value reaches the server before the button action runs
    "        setTimeout(function() { btn.click(); }, 300);" +
    "      }" +
    "      break;" +
    "    }" +
    "  }" +
    "}"
),
  1. In the button’s onAction method, read fv_flagId and use its value to perform the required operation. This successfully triggers the Servoy method from the flag click.

This is a workaround, not an official API, so a built-in way to send custom values from the browser to a form method would be a welcome feature.

Thanks again,
Aijaz

Thanks for sharing the full workaround, the hidden field plus button bridge is a neat way around the one-way limitation. One thing worth double-checking is that several charts or form instances on the same page could each have their own bridge elements, so the querySelector walk up from chart.canvas is a good choice since it keeps each chart tied to its own pair. I would also consider replacing the fixed 300 ms timeout with a short guard in the onAction method that ignores an empty fv_flagId, so a slow connection can’t trigger the action with a stale value.

1 Like

The hidden field plus hidden button bridge is a clever workaround, and keeping the elements rendered (visible = true with CSS hiding) is the detail people usually miss, since DOM lookup fails otherwise. One thing worth hardening: the style-class selectors could collide with other elements on the form, so scoping the query to the chart’s container would be safer. Also consider clearing fv_flagId after the onAction fires, so a later click on an identical value still triggers the button. I’d be interested whether the consumer reads the value in onAction directly or via the form variable.