# AJAX in OpenCart: JSON Responses from Controllers in 3.0 and 4.1

> How to write a controller method that returns JSON, call it via AJAX on the storefront and in the admin, and not break the response in OpenCart 3.0 and 4.1.

Джерело: https://opencartcode.com/en/wiki/dev-mvc/ajax-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-24

AJAX in OpenCart works like this: a separate public [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) method builds an array, encodes it as JSON, and returns it via `$this->response` with the `Content-Type: application/json` header. JavaScript calls this method through a regular `index.php?route=…`. The principle is the same in 3.0 and 4.1. The differences are the route format, class names, and how the 4.1 admin saves forms. Below we walk through the whole cycle: from the controller method to handling the response in the browser. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## What does an AJAX request to an OpenCart controller look like?

OpenCart has no separate "AJAX router". A request from JavaScript follows the same path as opening a regular page: `index.php` → framework initialization → router by the `route` parameter → controller method. This chain is described in detail in the article about [framework.php and the request path](https://opencartcode.com/en/wiki/dev-architecture/opencart-framework-php). So an AJAX endpoint is just a regular controller method. It does not render a template; it returns data.

```mermaid
sequenceDiagram
    participant B as Browser (jQuery)
    participant I as index.php + router
    participant C as Controller method
    participant M as Model / DB
    B->>I: GET/POST ?route=...check
    I->>C: call method
    C->>M: fetch data
    M-->>C: array
    C-->>B: JSON + Content-Type
    B->>B: update DOM / show error
```

This leads to an important point. Everything that applies to a regular request applies to an AJAX request: startup controllers, events, admin login checks, and the language and currency from the session. The method does not have to be separate. You can add it to your module's controller next to `index()`. How the core finds the right class and method from the `route` string is explained in the article about [route= routing in 3.0 and 4.1](https://opencartcode.com/en/wiki/dev-mvc/opencart-route).

The method must be public. Names starting with a double underscore are not called by the router. Accordingly, helper methods (validation, data preparation) should be `protected` or `private` so they cannot be reached from outside via a URL.

## How do you write a controller method that returns JSON?

The scheme is always the same. You create an array `$json` and fill it with the keys `error`, `success`, or data. At the end, you set the header and pass the encoded string to `setOutput()`. What the response object can do is described in the article about [Request and Response in OpenCart](https://opencartcode.com/en/wiki/dev-architecture/opencart-request-response).

### OpenCart 3.0

Example

```php
<?php
// catalog/controller/extension/module/stock_check.php
class ControllerExtensionModuleStockCheck extends Controller {
    public function check() {
        $this->load->language('extension/module/stock_check');

        $json = array();

        $product_id = isset($this->request->get['product_id']) ? (int)$this->request->get['product_id'] : 0;

        $this->load->model('catalog/product');
        $product_info = $this->model_catalog_product->getProduct($product_id);

        if (!$product_info) {
            $json['error'] = $this->language->get('error_product');
        } else {
            $json['quantity'] = (int)$product_info['quantity'];
            $json['in_stock'] = $product_info['quantity'] > 0;
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}
```

The route to the method is `extension/module/stock_check/check`. The last segment after the slash is the method name.

### OpenCart 4.1

Example

```php
<?php
// extension/stock_check/catalog/controller/module/stock_check.php
namespace Opencart\Catalog\Controller\Extension\StockCheck\Module;

class StockCheck extends \Opencart\System\Engine\Controller {
    public function check(): void {
        $this->load->language('extension/stock_check/module/stock_check');

        $json = [];

        $product_id = (int)($this->request->get['product_id'] ?? 0);

        $this->load->model('catalog/product');
        $product_info = $this->model_catalog_product->getProduct($product_id);

        if (!$product_info) {
            $json['error'] = $this->language->get('error_product');
        } else {
            $json['quantity'] = (int)$product_info['quantity'];
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}
```

Route: `extension/stock_check/module/stock_check.check`. In 4.1 the method is separated by a dot; the core automatically replaces the old separator `|` with a dot, but write a dot in new code.

> Do not finish a method with `echo json_encode($json); exit;`. This bypasses the Response object: events after the controller won't run, output compression and added headers will be skipped. Other modules that hook into your route will also get nothing. Return results only through `setOutput()`.

## How does AJAX differ in 3.0 and 4.1?

The approach to JSON is the same in both branches. The difference lies in the surrounding structure: where the files are, how the classes are named, and how much the admin itself relies on AJAX.

| Aspect | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Module controller file | `catalog/controller/extension/module/x.php` | `extension/назва/catalog/controller/module/x.php` |
| Class | `ControllerExtensionModuleX` | namespace `Opencart\Catalog\Controller\Extension\…`, class `X` |
| Method call in route | `…/module/x/method` | `…/module/x.method` |
| Saving forms in admin | regular POST and redirect | AJAX: form with `data-oc-toggle="ajax"`, JSON response |
| Language in storefront URL | taken from the session | `language=` parameter in links |
| Frontend | jQuery + Bootstrap 3 | jQuery 3 + Bootstrap 5 |

Porting a module from 3.0 to 4.1 usually takes the most time in the admin. In 3.0, the `index()` method itself accepted POST, validated the data, and performed `$this->response->redirect()`. In 4.1, `index()` only displays the form, while saving is handled by a separate `save()` method that always returns JSON. A redirect from such a method makes no sense: the browser would execute it inside XHR and receive HTML instead of JSON. If the user must be sent to another page after the action, put the URL in `$json['redirect']`. The standard 4.1 admin script and typical [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) code handle this key themselves.

The general structure of controllers, child controllers, and passing data to the template are described in the article "[OpenCart Controller: data, template, and child controllers](https://opencartcode.com/en/wiki/dev-mvc/opencart-controller)".

## How do you call a method from JavaScript and handle the response?

In both versions jQuery is already included, so the simplest option is to use `$.ajax`. Specify `dataType: 'json'` so that jQuery parses the response itself. Then invalid JSON will reach the `error` callback instead of being silently ignored.

Example (storefront, OpenCart 4.1)

```twig
<button type="button" id="button-stock" data-product-id="{{ product_id }}" class="btn btn-light">
  {{ button_check }}
</button>
<div id="stock-result"></div>

<script>
$('#button-stock').on('click', function () {
    var element = this;

    $.ajax({
        url: 'index.php?route=extension/stock_check/module/stock_check.check&language={{ language }}&product_id=' + $(element).data('product-id'),
        dataType: 'json',
        beforeSend: function () {
            $(element).prop('disabled', true);
        },
        complete: function () {
            $(element).prop('disabled', false);
        },
        success: function (json) {
            if (json['error']) {
                $('#stock-result').html('<div class="alert alert-danger">' + json['error'] + '</div>');
            }

            if (typeof json['quantity'] !== 'undefined') {
                $('#stock-result').text(json['quantity']);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
});
</script>
```

Pass the `language` variable to the template from the controller, for example `$data['language'] = $this->config->get('config_language');`. In 3.0 this parameter is not needed, and the route uses a slash: `extension/module/stock_check/check`. How to pass variables and safely output them in the template is explained in the article about [Twig in OpenCart](https://opencartcode.com/en/wiki/dev-mvc/opencart-twig-templates).

Do not remove the `error` block in `$.ajax`, even in production. The `xhr.responseText` output is the fastest way to see what the server actually returned: PHP warnings, a login page, or a fatal error.

> If the JSON contains Cyrillic, `json_encode()` escapes it by default as `\u04…`. The browser parses such a string without problems, but it is hard to read in the Network tab. While debugging, you can add the `JSON_UNESCAPED_UNICODE` flag.

## How does AJAX form saving work in the 4.1 admin?

In OpenCart 4.1 admin, module settings forms are submitted by the common admin script. It intercepts the submit of a form with the `data-oc-toggle="ajax"` [attribute](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#attribute), sends it as a POST to the address in `action`, and parses the JSON according to the agreed key names. `success` is shown as a green notification. `error.warning` is shown as a general warning. The remaining keys in `error` highlight the corresponding fields: for the key `threshold` the script looks for the field `#input-threshold` and the block `#error-threshold`. If you follow these names, you won't need to write custom JS for the settings form.

Example (admin, OpenCart 4.1)

```php
public function save(): void {
    $this->load->language('extension/stock_check/module/stock_check');

    $json = [];

    if (!$this->user->hasPermission('modify', 'extension/stock_check/module/stock_check')) {
        $json['error']['warning'] = $this->language->get('error_permission');
    }

    if ((int)($this->request->post['module_stock_check_threshold'] ?? 0) < 0) {
        $json['error']['threshold'] = $this->language->get('error_threshold');
    }

    if (!$json) {
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('module_stock_check', $this->request->post);

        $json['success'] = $this->language->get('text_success');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}
```

In `index()` the save address is formed like this: `$data['save'] = $this->url->link('extension/stock_check/module/stock_check.save', 'user_token=' . $this->session->data['user_token']);`. In the template it becomes the `action="{{ save }}"` attribute of the form with `data-oc-toggle="ajax"`. Take error and message texts from the module's [language file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) rather than hardcoding them in the code (see [language files and module translation](https://opencartcode.com/en/wiki/dev-mvc/opencart-language-files)).

You can check that everything works. Open "[Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → Extensions" (Розширення → Розширення), select the "Modules" type, and open your module for editing. Click "Save" and make sure the page did not reload and a notification appeared at the top.

Extensions → Modules: this is where the module form opens, which in 4.1 is saved via AJAX · OpenCart 4.1.0.4

## How do you protect an AJAX endpoint: user_token and permissions?

An AJAX method can be called directly from the address bar, so it must be protected the same way as a regular page, and even more carefully.

- **user_token in admin.** Without a valid `user_token` in the URL, the admin considers the request unauthorized and returns the login page. In JS this looks like a JSON parsing error. That is why the token must be in every AJAX address in the admin. Details are in the article about [user_token in the admin](https://opencartcode.com/en/wiki/dev-mvc/opencart-user-token).
- **User group permissions.** The `hasPermission('modify', …)` check is mandatory in any method that changes data. For read-only methods, check `access`. How the core maps a route to permissions is covered in the article "[Module access permissions](https://opencartcode.com/en/wiki/dev-mvc/opencart-module-access-permissions)".
- **Type casting.** Everything from `$this->request` is user data. Cast identifiers to `(int)`, and escape strings for SQL via `$this->db->escape()` in the model. Do not write raw queries in the controller (see [models and $this->db](https://opencartcode.com/en/wiki/dev-mvc/opencart-model)).
- **Minimum data in the response.** Do not return the entire database row to the storefront. Return only the fields the JS needs, without cost prices, internal notes, or other customers' data.
- **Actions in the storefront.** If a method changes state (cart, wishlist, subscription), accept only POST and verify that the required data is in the session. Relying on "nobody will find the button" is not acceptable.

## Why does AJAX return an error instead of JSON, and how do you debug it?

The most common symptom is `SyntaxError: Unexpected token <` or `parsererror` in the console. It means HTML arrived before the JSON or instead of it. Typical causes:

1. **PHP warning or notice.** If error display is enabled, the Warning text is output before the JSON and breaks it. Turn off error display in "System → Settings" (Система → Настройки), the "Server" tab, and keep logging to a file.
2. **Stray output in files.** A space or empty line after the closing `?>` or a BOM in a UTF-8 file ends up in the output. It is better not to include a closing PHP tag at all in the module's PHP files.
3. **Login page.** The session expired or `user_token` was not passed, and the admin returned the login form HTML.
4. **Wrong route.** A slash instead of a dot in 4.1, a dot in 3.0, or an error in the class name leads to a "not found" page instead of JSON.
5. **Debug output.** A forgotten `var_dump()` or `print_r()` in the model.

Settings → Server tab: turn off error display, keep logging to file · OpenCart 4.1.0.4

The fastest source of truth is the Network tab in developer tools. Open the request and look at the raw response text. Then check the log in "System → Maintenance → Error Logs" (Система → Обслуговування → Журнал помилок): it will show notices and fatal errors that are not visible in the browser.

Error log: PHP warnings that break the JSON response are visible here · OpenCart 4.1.0.4

Another pitfall is full-page caching by third-party modules. If the cache stores responses by URL, a GET endpoint returning stock or price data may serve stale results. Add such routes to the cache exceptions or switch them to POST.

## Summary

- An AJAX endpoint in OpenCart is a regular public controller method. It builds an `$json` array, sets the `Content-Type: application/json` header, and returns the result via `$this->response->setOutput(json_encode($json))`.
- In 3.0 the method is specified in the route with a slash (`…/x/check`), in 4.1 with a dot (`…/x.check`). In the 4.1 storefront, add the `language` parameter to the URL.
- In the 4.1 admin, form saving works via AJAX. A separate `save()` method returns the `success`, `error.warning`, and `error.поле` keys, and to redirect to another page, use `redirect` in the JSON instead of a server-side redirect.
- Protection is mandatory: `user_token`, `hasPermission()`, type casting, and minimal data in the response.
- If the JSON "doesn't parse", look at the raw response in the Network tab and the error log.

Next, it is worth learning how the controller passes data to the Twig template and how to organize the module's language files. All articles in this section are collected on the page [MVC-L: controllers, models, templates](https://opencartcode.com/en/wiki/dev-mvc).

## FAQ

**Can I use fetch instead of jQuery $.ajax in OpenCart?**

Yes, the backend doesn't care how the request was sent. Just pass the same route, user_token and language parameters. For POST with fetch, it's convenient to send FormData, and the data will then end up in $this->request->post as usual.

**How do I send JSON in the request body instead of form-data?**

OpenCart fills $this->request->post only from form-urlencoded or multipart data. You'll have to read the raw JSON body via file_get_contents('php://input') and json_decode it. It's simpler to send regular form fields.

**How do I refresh the header mini cart after an AJAX add-to-cart?**

After a successful response, reload the cart block with a separate request to the common/cart route with the info method: in 3.0 using a slash, in 4.1 using a dot. This is how standard themes do it.

**Do I need to set an HTTP response code for errors?**

Standard OpenCart returns errors with code 200 and passes them in the error key. You can set a different status via a header, but then the success handler in jQuery won't fire, and you'll have to handle the error in the error callback.

**Can I call one module's AJAX method from another module's controller?**

It's better to move the logic into a model and call it from both controllers. A method that writes JSON to the Response isn't meant for reuse via load->controller.
