In addition to the response from Guilherme , we can also make the request with pure JavaScript through the fetch
. It is still an experimental tool yet, but it is already supported in major browsers and has a polyfill if you need support in other browsers.
With fetch
, a POST request that sends the data of a form, for example, would be similar to:
const data = new FormData( document.getElementById('form') );
const request = fetch('pagina.php', {method: 'POST', body: data});
request.then(response => {
if (response.ok) {
// A requisição foi feita com sucesso...
} else {
// Algo de errado não está certo...
}
});
request.catch(error => {
// Parece que tem algo errado no 'fetch'...
});
The fetch
function basically returns a promise and, if you understand what a promise is, the code is very easy to understand. The first parameter of the function is a URI that identifies the resource on the server, while the second parameter is an object that configures the request, in this case, defining the request method and the data sent by the request body.
If you like semantics, you can leave the code more semantic. In the fetch
API itself some classes are defined that help in this part, to mention: Request
, Headers
and Response
. This way, you can set the headers of your request through Headers
:
const headers = new Headers({'Origin': '...'});
headers.append('X-Custom-Header', '...');
And the request through class Request
:
const request = new Request('pagina.php', {method: 'POST', headers: headers, body: data});
Passing object request
to function fetch
:
fetch(request).then(response => { ... });
So, when the request is made, the parameter response
passed to the callback function will be an instance of class Response
.
Read more on % specification for WHATWG .