# Call another address with AJAX() from the server

> Use AJAX() to call an HTTP address with a JSON body and get the parsed answer, as a promise or with a callback, and know what happens with errors and XML.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 761c3549df81c70a95b4da31e4770d745833c6240cfc45d2c310f79cd7d43d8f
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`AJAX('METHOD url', [data], [callback])` makes an HTTP request and gives you the **parsed** answer. It is the short form of `REQUEST()` for APIs that talk JSON: the same call that jComponent has in the browser, so the code of the page and of the server look alike.

- The address starts with an optional method: `AJAX('POST https://example.com/api/', data)`. Without a method it is a `GET`.
- `data`, when given, is sent as a **JSON body**. The request carries the header `x-requested-with: XMLHttpRequest`, so on the other side `$.xhr` is `true`.
- The answer is parsed by its content type: JSON becomes an object, `application/x-www-form-urlencoded` becomes an object, anything else arrives as text.
- When the status is 400 or more, the promise is **rejected** (or the callback gets the error first) with the parsed body of the answer as the error. A callback is called as `callback(err, value, response)`.
- Without a callback it returns a promise.

**For XML answers use `REQUEST()`** and parse the body yourself: `AJAX()` is made for JSON and text answers.

The example calls routes of the same application, whose address `$.hostname('/')` gives, so that it needs no other server.

```js controllers/calls.js
exports.install = function() {
	ROUTE('GET /api/hello/', hello);
	ROUTE('POST /api/echo/', echo);
	ROUTE('GET /api/text/', text);
	ROUTE('GET /api/xml/', xml);
	ROUTE('GET /api/fail/', fail);
	ROUTE('GET /calls/', calls);
};

function hello($) {
	$.json({ hello: 'world', xhr: $.xhr });
}

function echo($) {
	$.json({ received: $.body, xhr: $.xhr });
}

function text($) {
	$.plain('plain text');
}

function xml($) {
	$.xml('<a><b>1</b></a>');
}

function fail($) {
	$.invalid('It is wrong');
}

async function calls($) {

	const base = $.hostname('/');
	const out = {};

	out.hello = await AJAX('GET ' + base + 'api/hello/');
	out.nomethod = await AJAX(base + 'api/hello/');
	out.echo = await AJAX('POST ' + base + 'api/echo/', { a: 1 });
	out.text = await AJAX(base + 'api/text/');

	try {
		await AJAX(base + 'api/fail/');
	} catch (err) {
		out.error = err.message || err;
	}

	out.callback = await new Promise(resolve => AJAX(base + 'api/hello/', (err, value, response) => resolve({ err: err, hello: value.hello, status: response.status })));

	out.xml = await Promise.race([
		AJAX(base + 'api/xml/').then(() => 'answered', () => 'rejected'),
		new Promise(resolve => setTimeout(() => resolve('never answered'), 1000))
	]);

	$.json(out);
}
```
