javascriptphpajaxactionelgg

How to add an AJAX action - Elgg


I'm trying to create an AJAX action in elgg. 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

<?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 ?>
</div>

start.php

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

action file: actions/service_comments/add.php

<?php

    elgg_ajax_gatekeeper();

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

    // will be rendered client-side
    system_message('We did it!');

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

Javascript : views/js/service_comments/add.js

var Ajax = require('elgg/Ajax');
var ajax = new Ajax();

ajax.action('service_comments/add', {
  data: {
    arg1: 1,
    arg2: 2
  },
}).done(function (output, statusText, jqXHR) {
  if (jqXHR.AjaxData.status == -1) {
    return;
  }
  alert(output.sum);
  alert(output.product);
});

Solution

  • You have written ajax procedure but not invoking it. Instead you are directly calling it . by making it link.

        $params_confirm = array(
        'href' => '#',
        'text' => elgg_view_icon('upload'),
        'onclick' => "myajax_function()",
        'class' => 'upload-media-update',
        );
    
    $confirm = elgg_view('output/url', $params_confirm);
    

    Then move your JS code inside a function.

    function myajax_function(){
      var Ajax = require('elgg/Ajax');
      var ajax = new Ajax();
    
      ajax.action('service_comments/add', {
               data: {
               arg1: 1,
               arg2: 2
           },
      }).done(function (output, statusText, jqXHR) {
             if (jqXHR.AjaxData.status == -1) {
          return;
      }
      alert(output.sum);
      alert(output.product);
     });
    }