In addition to the William, we can also request with pure Javascript through the API fetch
. At the moment, it is still an experimental tool, but already has support in the main browsers and has a polyfill if you need support in other browsers.
With the fetch
, a POST request that sends the data of a form, for example, would look 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 function fetch
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 body of the same.
If you like semantics, you can make the code more semantic. In the API itself fetch
are defined some classes that help in this part, to quote: 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 the class Request
:
const request = new Request('pagina.php', {method: 'POST', headers: headers, body: data});
Passing the object request
for the function fetch
:
fetch(request).then(response => { ... });
Thus, when the request is made, the parameter response
function callback will be an instance of the class Response
.
Read more on specification of fetch
on WHATWG.
Since you did not advertise let me do for you : "You can also use the Lib Pjax and leave your dynamic page with no need to reload everything again"
– Guilherme Lautert
It’s a great lib expose her :D
– Guilherme Lautert
@Guilhermelautert kkkkk, is almost coming out version 0.6.0, which I intend to be "more practical" :) - I will post on that question about Pjax himself, but thanks for remembering, I need to be less humble and start making more jabas hehe
– Guilherme Nascimento