AJAX in OpenCart works like this: a separate public controllerCode that receives a request and prepares data. More in the glossary → method builds an array, encodes it as JSON, and returns it via $this->response with the Content-Type: application/ 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. So an AJAX endpoint is just a regular controller method. It does not render a template; it returns data.
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.
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.
OpenCart 3.0
Example
<?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/. The last segment after the slash is the method name.
OpenCart 4.1
Example
<?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/. 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.
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/ | extension/ |
| 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. 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 storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → 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".
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)
<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. In 3.0 this parameter is not needed, and the route uses a slash: extension/. How to pass variables and safely output them in the template is explained in the article about Twig in OpenCart.
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.
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" attributeA product characteristic that does not affect the price: material, weight, power. It is set in "Catalog → Attributes" and displayed on the "Specification" tab. More in the glossary →, 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)
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. 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 fileA PHP file with interface texts, separate for each language. More in the glossary → rather than hardcoding them in the code (see language files and module translation).
You can check that everything works. Open "ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → → 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.

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_tokenin 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. - User group permissions. The
hasPermission('modify', …)check is mandatory in any method that changes data. For read-only methods, checkaccess. How the core maps a route to permissions is covered in the article "Module access permissions". - Type casting. Everything from
$this->requestis user data. Cast identifiers to(int), and escape strings for SQL via$thisin the model. Do not write raw queries in the controller (see models and $this->db).->db ->escape() - 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:
- 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.
- 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. - Login page. The session expired or
user_tokenwas not passed, and the admin returned the login form HTML. - 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.
- Debug output. A forgotten
var_dump()orprint_r()in the model.

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.

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
$jsonarray, sets theContent-Type: application/header, and returns the result viajson $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 thelanguageparameter to the URL. - In the 4.1 admin, form saving works via AJAX. A separate
save()method returns thesuccess,error.warning, anderror.полеkeys, and to redirect to another page, useredirectin 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.