javascriptphphtmlajaxelgg

How to make AJAX calls - Elgg


I'm trying to make an AJAX call in elgg, but I've been unsuccessful so far. What could I be doing wrong, or what am I missing?

Thank you all in advance.

Elgg version 2.1.1

start.php

// in myplugin_init()
elgg_register_ajax_view('forms/myplugin/add');

default/forms/myplugin/add.php

<div>Successful AJAX call</div>

default/object/my_ajax_plugin.php

<div class="myplugin-form-container">JQ Here</div>

<script type = "text/javascript" language = "javascript">

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

    ajax.form('myplugin/add').done(function (output, statusText, jqXHR) {
        if (jqXHR.AjaxData.status == -1) {
            return;
        }
            $('.myplugin-form-container').html(output);
    });

</script>

Solution

  • Elgg uses requirejs for dependencies loading. You can't just throw require inline and expect it to work. You could try:

    require(['elgg/Ajax'], Ajax => {
      var ajax = new Ajax();
      ajax.view('developers/ajax_demo.html').then(body => {
        console.log('RESULT', body)
      })
    })