ForgejComponent
en

jComponent

Call Total.js API routes with API()

jComponent 20 · jcomponent@20 jcomponentfrontendajaxapi Executed with jComponent 20

API(url, name, data, callback) is the client side of the Total.js ROUTE('API ...') endpoints. It sends POST url with the body { schema: name, data: data } and calls the callback with the response. When the server answers with an error (for example a validation error) the callback receives an array of errors: use the ERROR(response, success, error) helper to handle both cases in one place.

Put the address of the endpoint in ENV() once and reuse it.

definitions/math.js
NEWACTION('Math/add', {
	name: 'Add two numbers',
	input: '*a:Number, *b:Number',
	action: function($, model) {
		$.callback({ sum: model.a + model.b });
	}
});
controllers/api.js
exports.install = function() {
	ROUTE('API /api/ +math_add --> Math/add');
};
public/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>jComponent</title>
	<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
	<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
	<p class="sum"></p>
	<p class="error"></p>

	<script>

		ENV('api', '/api/');

		API('[api]', 'math_add', { a: 20, b: 22 }, function(response) {
			SET('sum', response.sum);
		});

		API('/api/', 'math_add', { a: 'x' }, function(response) {
			ERROR(response, function(value) {
				SET('failed', 'unexpected success');
			}, function(errors) {
				SET('failed', errors[0].name);
			});
		});

	</script>

</body>
</html>
Try it in your browser

Edit the example and run it. It runs in an isolated frame in your browser; nothing is sent to our server.

Preview