How to add an AJAX action

I'm trying to create an AJAX action. I have followed this Elgg tutorial: Ajax: Performing actions, but I'm getting nothing so far, apart from the fail error:

Sorry, Ajax only!

The other error is that the page reloads, instead of persisting the data asynchronously.

What am I getting wrong? Thank you all in advance.

Below is my code:

form: views/default/forms/service_comments/add.php

    $url_confirm = elgg_add_action_tokens_to_url("action/service_comments/add?guid={$guid}");
    $params_confirm = array(
        'href' => $url_confirm,
        'text' => elgg_view_icon('upload'),
        'is_action' => true,
        'is_trusted' => true,
        'class' => 'upload-media-update',

    $confirm = elgg_view('output/url', $params_confirm);

<div class="update-options">
    <?= $confirm ?>


elgg_register_action("service_comments/add", __DIR__ . "/actions/service_comments/add.php");

action file: actions/service_comments/add.php


    if (!elgg_is_xhr()) {
        register_error('Sorry, Ajax only!');

    $arg1 = (int)get_input('arg1');
    $arg2 = (int)get_input('arg2');

    system_message('We did it!');

    echo json_encode([
        'sum' => $arg1 + $arg2,
        'product' => $arg1 * $arg2,

Javascript : views/js/service_comments/add.js

elgg.action('service_comments/add', {
  data: {
    arg1: 1,
    arg2: 2
  success: function (wrapper) {
    if (wrapper.output) {
    } else {
      // the system prevented the action from running
Beginning Developers

Beginning Developers

This space is for newcomers, who wish to build a new plugin or to customize an existing one to their liking