# Chiama un altro indirizzo con AJAX() dal server

> Usa AJAX() per chiamare un indirizzo HTTP con un corpo JSON e ottenere la risposta già interpretata, come promise o con callback, e scopri cosa succede con gli errori e con XML.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 803efc3671c386d39e3984c4a909a9755de1442255e6a5b1c98fdc014e20fea4
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`AJAX('METHOD url', [data], [callback])` fa una richiesta HTTP e ti dà la risposta **interpretata**. È la forma breve di `REQUEST()` per le API che parlano JSON: la stessa chiamata che jComponent ha nel browser, così il codice della pagina e quello del server si somigliano.

- L'indirizzo inizia con un metodo facoltativo: `AJAX('POST https://example.com/api/', data)`. Senza metodo è un `GET`.
- `data`, quando è dato, viene inviato come **corpo JSON**. La richiesta porta l'intestazione `x-requested-with: XMLHttpRequest`, quindi dall'altra parte `$.xhr` è `true`.
- La risposta viene interpretata in base al suo tipo di contenuto: il JSON diventa un oggetto, `application/x-www-form-urlencoded` diventa un oggetto e qualsiasi altra cosa arriva come testo.
- Quando lo stato è 400 o superiore, la promise viene **rifiutata** (o il callback riceve prima l'errore) con il corpo interpretato della risposta come errore. Un callback viene chiamato come `callback(err, value, response)`.
- Senza callback restituisce una promise.

**Per le risposte XML usa `REQUEST()`** e analizza tu il corpo: `AJAX()` è pensato per risposte JSON e di testo.

L'esempio chiama route della stessa applicazione, il cui indirizzo è dato da `$.hostname('/')`, così non ha bisogno di nessun altro 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);
}
```
