PHPackages                             heimrichhannot/contao-ajax - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. heimrichhannot/contao-ajax

Abandoned → [heimrichhannot/contao-ajax-bundle](/?search=heimrichhannot%2Fcontao-ajax-bundle)Contao-module[Utility &amp; Helpers](/categories/utility)

heimrichhannot/contao-ajax
==========================

Keep contao ajax requests organized and handle responses with ease.

1.3.2(2y ago)114.4k6LGPL-3.0-or-laterPHPPHP ~5.4 || ~7.0 || ^8.0

Since Aug 4Pushed 2y ago4 watchersCompare

[ Source](https://github.com/heimrichhannot/contao-ajax)[ Packagist](https://packagist.org/packages/heimrichhannot/contao-ajax)[ Docs](https://github.com/heimrichhannot/contao-ajax)[ RSS](/packages/heimrichhannot-contao-ajax/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (35)Used By (6)

Ajax
====

[](#ajax)

[![](https://camo.githubusercontent.com/5332a329ec8d9ef8e49d62b81a97ea5509223d48c7eb1e3d58d9fb452b583343/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6865696d7269636868616e6e6f742f636f6e74616f2d616a61782e737667)](https://camo.githubusercontent.com/5332a329ec8d9ef8e49d62b81a97ea5509223d48c7eb1e3d58d9fb452b583343/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6865696d7269636868616e6e6f742f636f6e74616f2d616a61782e737667)[![](https://camo.githubusercontent.com/8f56f23c99806bc414b1ab7fbf575475ce17bdd83dd6e43e0f21404156ec38e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6865696d7269636868616e6e6f742f636f6e74616f2d616a61782e737667)](https://camo.githubusercontent.com/8f56f23c99806bc414b1ab7fbf575475ce17bdd83dd6e43e0f21404156ec38e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6865696d7269636868616e6e6f742f636f6e74616f2d616a61782e737667)[![](https://camo.githubusercontent.com/c4a6f4ae5ddb0f49d23f947b46910edde6e69f5aef0ff795a403ab20ebd4ba32/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6865696d7269636868616e6e6f742f636f6e74616f2d616a61782f6d61737465722e737667)](https://travis-ci.org/heimrichhannot/contao-ajax/)[![](https://camo.githubusercontent.com/820c25629084336bc10315c5727b9c500847f5511a95b201934bc7c7b986fb76/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f6865696d7269636868616e6e6f742f636f6e74616f2d616a61782f6d61737465722e737667)](https://coveralls.io/github/heimrichhannot/contao-ajax)

Ajax requests within contao are not centralized by default. Due to the handling of ajax requests within different types of modules a simple \\Environment::get('isAjaxRequest') is not enough to delegate the request to the related module / method. This module provides a global configuration, where you can attach your module within `$GLOBALS['AJAX']` as a custom group and add your actions with the required parameters that should be checked against the request.

Technical instruction
---------------------

[](#technical-instruction)

The following section will show you how your custom ajax actions can be registered and triggered.

### 1. Configuration / Setup

[](#1-configuration--setup)

The following example shows the \[heimrichhannot/contao-formhybrid\] () ajax configuration.

```
config.php
/**
 * Ajax Actions
 */
$GLOBALS['AJAX'][\HeimrichHannot\FormHybrid\Form::FORMHYBRID_NAME] = array
(
	'actions' => array
	(
		'toggleSubpalette' => array
		(
			'arguments' => array('subId', 'subField', 'subLoad'),
			'optional'   => array('subLoad'),
		),
		'asyncFormSubmit'  => array
		(
			'arguments' => array(),
			'optional'   => array(),
		),
		'reload'  => array
		(
			'arguments' => array(),
			'optional'   => array(),
			'csrf_protection' => true, // cross-site request forgery (ajax token check)
		),
	),
);

```

As you can see, we have a group `formhybrid` that delegates all ajax request with this `group` parameter to formhybrid. Then there are some actions `toggleSubpalette`, `asyncFormSubmit` and so on. These mehtod must be present with the same name in the delegated context. You can provide arguments, that should be called within the function and added as arguments to the method. If the argument is `optional`, than the request will be valid if the argument is not present, otherwise all `arguments` must be present in the request, to have a valid ajax request. If you want to protect the ajax request against cross site violations, than add `csrf_protection => true` to your configuration and dont forget to update the ajax url on each request!

### 2. How can i create the url to my ajax action?

[](#2-how-can-i-create-the-url-to-my-ajax-action)

We provide a simple helper method within `HeimrichHannot\Ajax\AjaxAction` that is called `generateUrl`. The following example shows, how we create the `toggleSubpalette` url within `FormHybrid`.

```
\HeimrichHannot\Ajax\AjaxAction::generateUrl(Form::FORMHYBRID_NAME, 'toggleSubpalette')

```

As you can see, we do not add the arguments by default. This is done within the associated javascript code for `toggleSubpalette`. You have to check within your javascript code, that the arguments `subId`, `subField`, `subLoad` are provided as $\_POST parameters within the ajax request by your own.

```
jquery.formhybrid.js

toggleSubpalette: function (el, id, field, url) {
    el.blur();
    var $el = $(el),
        $item = $('#' + id),
        $form = $el.closest('form'),
        checked = true;

    var $formData = $form.serializeArray();

    $formData.push(
        {name: 'FORM_SUBMIT', value: $form.attr('id')},
        {name: 'subId', value: id},
        {name: 'subField',value: field});

    if ($el.is(':checkbox') || $el.is(':radio')) {
        checked = $el.is(':checked');
    }

    if (checked === false) {

        $.ajax({
            type: 'post',
            url: url,
            dataType: 'json',
            data: $formData,
            success: function (response) {
                $item.remove();
            }
        });

        return;
    }

    $formData.push(
        {name: 'subLoad', value: 1}
    );

    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: $formData,
        success: function (response, textStatus, jqXHR) {
            $item.remove();
            // bootstrapped forms
            if ($el.closest('form').find('.' + field).length > 0) {
                // always try to attach subpalette after wrapper element from parent widget
                $el.closest('form').find('.' + field).eq(0).after(response.result.html);
            } else {
                $el.closest('#ctrl_' + field).after(response.result.html);
            }
        }
    });
}

```

### 3. How are my ajax actions triggered?

[](#3-how-are-my-ajax-actions-triggered)

The give you the biggest possible freedom, we decided to be always within contao context. Therefore all request preconditions are checked within the default contao request-cycle.

In case of the `toggleSubpalette` example we trigger the action within `DC_Hybrid::__construct()` and provide a `new FormAjax($this)` as Response Context.

CAUTION: Don't call "runActiveAction" in generate() of a Contao module since that's too late. It's always best to run it in \_\_construct().

```
DC_Hybrid.php

public function __construct($strTable = '', $varConfig = null, $intId = 0)
{
    ...

    Ajax::runActiveAction(Form::FORMHYBRID_NAME, 'toggleSubpalette', new FormAjax($this));

    ...

}

```

#### So what is done here?

[](#so-what-is-done-here)

1. The ajax action is requested from your javascript code.
2. The ajax action is delegated to the current page, where our `DC_Hybrid` extended Module is available.
3. The `Ajax` Controller will check the request against the given parameters for `toggleSubpalette` from the `$GLOBALS['AJAX']` config.
4. If all requirements were meet, and the method `toggleSubpalette` is available within the given context `new FormAjax($this)`, the method is trigged with the given arguments.
5. Now you can do your module related stuff within `toggleSubpalette`
6. If you want to return data to the ajax request, then you have to return a valid `HeimrichHannot\Ajax\Response\Response` Object.
7. The returned `HeimrichHannot\Ajax\Response\Response` Object will be converted to a JSON Object and the request will end here.

Response Objects
----------------

[](#response-objects)

Currently we implemented three response objects.

1. `HeimrichHannot\Ajax\Response\ResponseSuccess`
2. `HeimrichHannot\Ajax\Response\ResponseError`
3. `HeimrichHannot\Ajax\Response\ResponseRedirect`

### ResponseSuccess

[](#responsesuccess)

This will return a JSON Object with the HTTP-Statuscode `HTTP/1.1 200 OK` to the ajax action.

#### Example:

[](#example)

##### Client-Side:

[](#client-side)

```
$.ajax({
    type: 'post',
    url: url,
    dataType: 'json',
    data: $formData,
    success: function (response, textStatus, jqXHR) {
        $item.remove();
        // bootstrapped forms
        if ($el.closest('form').find('.' + field).length > 0) {
            // always try to attach subpalette after wrapper element from parent widget
            $el.closest('form').find('.' + field).eq(0).after(response.result.html);
        } else {
            $el.closest('#ctrl_' + field).after(response.result.html);
        }
    }
});

```

##### Server-Side:

[](#server-side)

```
/**
 * Toggle Subpalette
 * @param      $id
 * @param      $strField
 * @param bool $blnLoad
 *
 * @return ResponseError|ResponseSuccess
 */
function toggleSubpalette($id, $strField, $blnLoad = false)
{
    $varValue = Request::getPost($strField) ?: 0;

    if (!is_array($this->dca['palettes']['__selector__']) || !in_array($strField, $this->dca['palettes']['__selector__'])) {
        \Controller::log('Field "' . $strField . '" is not an allowed selector field (possible SQL injection attempt)', __METHOD__, TL_ERROR);

        return new ResponseError();
    }

    $arrData = $this->dca['fields'][$strField];

    if (!Validator::isValidOption($varValue, $arrData, $this->dc)) {
        \Controller::log('Field "' . $strField . '" value is not an allowed option (possible SQL injection attempt)', __METHOD__, TL_ERROR);

        return new ResponseError();
    }

    if (empty(FormHelper::getFieldOptions($arrData, $this->dc))) {
        $varValue = (intval($varValue) ? 1 : '');
    }

    $this->dc->activeRecord->{$strField} = $varValue;

    $objResponse = new ResponseSuccess();

    if ($blnLoad)
    {
        $objResponse->setResult(new ResponseData($this->dc->edit(false, $id)));
    }

    return $objResponse;
}

```

### ResponseError

[](#responseerror)

This will return a JSON Object with the HTTP-Statuscode `HTTP/1.1 400 Bad Request` to the ajax action.

#### Example:

[](#example-1)

##### Client-Side:

[](#client-side-1)

```
 $.ajax({
    url: url ? url : $form.attr('action'),
    dataType: 'json',
    data: $formData,
    method: $form.attr('method'),
    error: function(jqXHR, textStatus, errorThrown){
        if (jqXHR.status == 400) {
            alert(jqXHR.responseJSON.message);
            return;
        }
    }
});

```

##### Server-Side:

[](#server-side-1)

```
$objResponse = new ResponseRedirect();
$objResponse->setUrl($strUrl);
return $objResponse;

```

### ResponseRedirect

[](#responseredirect)

This will return a JSON Object with the HTTP-Statuscode `HTTP/1.1 301 Moved Permanently` to the ajax action. The redirect url is provided within the xhr response object `result.data.url`;

#### Example:

[](#example-2)

##### Client-Side:

[](#client-side-2)

```
 $.ajax({
    url: url ? url : $form.attr('action'),
    dataType: 'json',
    data: $formData,
    method: $form.attr('method'),
    error: function(jqXHR, textStatus, errorThrown){
        if (jqXHR.status == 301) {
            location.href = jqXHR.responseJSON.result.data.url;
            return;
        }
    }
});

```

##### Server-Side:

[](#server-side-2)

```
$objResponse = new ResponseRedirect();
$objResponse->setUrl($strUrl);
die(json_encode($objResponse));

```

Unit Testing
------------

[](#unit-testing)

For unit testing, define the variable `UNIT_TESTING` as `true` within the $GLOBALS.

```
//bootstrap.php

define('UNIT_TESTING', true);

```

Than you are able to catch the ajax result within you test, by catching the `HeimrichHannot\Ajax\Exception\AjaxExitException`.

```
// MyTestClass.php

    /**
     * @test
     */
    public function myTest()
    {
        $objRequest = \Symfony\Component\HttpFoundation\Request::create('http://localhost' . AjaxAction::generateUrl('myAjaxGroup', 'myAjaxAction'), 'post');

        $objRequest->headers->set('X-Requested-With', 'XMLHttpRequest'); // xhr request

        Request::set($objRequest);

		$objForm = new TestPostForm();

        try
        {
            $objForm->generate();
            // unreachable code: if no exception is thrown after form was created, something went wrong
            $this->expectException(\HeimrichHannot\Ajax\Exception\AjaxExitException::class);
        } catch (AjaxExitException $e)
        {
            $objJson = json_decode($e->getMessage());

            $this->assertTrue(strpos($objJson->result->html, 'id="my_css_id"') > 0); // check that id is present within response
        }
    }

```

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~83 days

Recently: every ~550 days

Total

34

Last Release

829d ago

PHP version history (2 changes)1.1.1PHP ~5.4 || ~7.0

1.3.0PHP ~5.4 || ~7.0 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/28ad3224d8727b622ebd229840eea6b9dbcb83eb0bd609e6ce65b614830ff538?d=identicon)[digitales@heimrich-hannot.de](/maintainers/digitales@heimrich-hannot.de)

---

Top Contributors

[![koertho](https://avatars.githubusercontent.com/u/12064642?v=4)](https://github.com/koertho "koertho (2 commits)")[![nafetagrats](https://avatars.githubusercontent.com/u/5796948?v=4)](https://github.com/nafetagrats "nafetagrats (1 commits)")[![vvohh](https://avatars.githubusercontent.com/u/75325799?v=4)](https://github.com/vvohh "vvohh (1 commits)")

---

Tags

responserequestajaxcontao

### Embed Badge

![Health badge](/badges/heimrichhannot-contao-ajax/health.svg)

```
[![Health](https://phpackages.com/badges/heimrichhannot-contao-ajax/health.svg)](https://phpackages.com/packages/heimrichhannot-contao-ajax)
```

###  Alternatives

[richardhj/contao-ajax_reload_element

AjaxReloadElement for Contao OpenSource CMS

144.2k](/packages/richardhj-contao-ajax-reload-element)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
