Skip to content

Commit 474fb3a

Browse files
authored
Merge pull request #203 from tcelestino/migrando-xmlhttp-para-fetch-api
Migrando XMLHttpRequest para Fetch api
2 parents f4acc8b + 06d67ad commit 474fb3a

File tree

3 files changed

+74
-62
lines changed

3 files changed

+74
-62
lines changed

public/main.js

Lines changed: 36 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,36 +23,42 @@ document.addEventListener(
2323
false
2424
);
2525

26-
function upVote(postId, object) {
27-
// Exemplo de requisição POST
28-
const ajax = new XMLHttpRequest();
29-
30-
// Seta tipo de requisição: Post e a URL da API
31-
ajax.open("POST", orbitaApi.restURL + 'orbitaApi/v1/likes', true);
32-
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
33-
ajax.setRequestHeader("X-WP-Nonce", orbitaApi.restNonce);
34-
35-
// Seta paramêtros da requisição e envia a requisição
36-
ajax.send("post_id=" + postId);
37-
38-
// Cria um evento para receber o retorno.
39-
ajax.onreadystatechange = function () {
40-
// Caso o state seja 4 e o http.status for 200, é porque a requisiçõe deu certo.
41-
if (ajax.readyState === 4 && ajax.status === 200) {
42-
const data = ajax.responseText;
43-
44-
const jsonData = JSON.parse(data);
45-
if (jsonData.success) {
46-
const textToUpdate = document.querySelector(
47-
"[data-votes-post-id='" + postId + "']"
48-
);
49-
textToUpdate.innerHTML = jsonData.count;
50-
51-
object.classList.add("orbita-vote-already-voted");
52-
object.classList.remove("orbita-vote-can-vote");
53-
}
54-
}
26+
async function upVote(postId, object) {
27+
const url = `${orbitaApi.restURL}orbitaApi/v1/likes`;
28+
const formData = new URLSearchParams();
29+
formData.append('post_id', postId);
30+
31+
const headers = {
32+
'Content-Type': 'application/x-www-form-urlencoded',
33+
'X-WP-Nonce': orbitaApi.restNonce,
5534
};
35+
36+
try {
37+
const response = await fetch(url, {
38+
method: 'POST',
39+
headers,
40+
body: formData.toString(),
41+
});
42+
43+
if (!response.ok) {
44+
throw new Error(`HTTP error! status: ${response.status}`);
45+
}
46+
47+
const jsonData = await response.json();
48+
49+
if (jsonData.success) {
50+
const textToUpdate = document.querySelector(
51+
`[data-votes-post-id='${postId}']`,
52+
);
53+
textToUpdate.innerHTML = jsonData.count;
54+
55+
object.classList.add('orbita-vote-already-voted');
56+
object.classList.remove('orbita-vote-can-vote');
57+
}
58+
59+
} catch (error) {
60+
throw new Error('Erro ao enviar voto:', error);
61+
}
5662
}
5763

5864
// Verifica o tamanho da imagem anexada ao post antes de enviar
@@ -100,4 +106,4 @@ function toggleAttachUrl() {
100106

101107
postUrlInput.addEventListener('input', toggleAttachUrl);
102108
postAttachInput.addEventListener('input', toggleAttachUrl);
103-
}
109+
}

public/main.min.js

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/js/main.js

Lines changed: 36 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,36 +23,42 @@ document.addEventListener(
2323
false
2424
);
2525

26-
function upVote(postId, object) {
27-
// Exemplo de requisição POST
28-
const ajax = new XMLHttpRequest();
29-
30-
// Seta tipo de requisição: Post e a URL da API
31-
ajax.open("POST", orbitaApi.restURL + 'orbitaApi/v1/likes', true);
32-
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
33-
ajax.setRequestHeader("X-WP-Nonce", orbitaApi.restNonce);
34-
35-
// Seta paramêtros da requisição e envia a requisição
36-
ajax.send("post_id=" + postId);
37-
38-
// Cria um evento para receber o retorno.
39-
ajax.onreadystatechange = function () {
40-
// Caso o state seja 4 e o http.status for 200, é porque a requisiçõe deu certo.
41-
if (ajax.readyState === 4 && ajax.status === 200) {
42-
const data = ajax.responseText;
43-
44-
const jsonData = JSON.parse(data);
45-
if (jsonData.success) {
46-
const textToUpdate = document.querySelector(
47-
"[data-votes-post-id='" + postId + "']"
48-
);
49-
textToUpdate.innerHTML = jsonData.count;
50-
51-
object.classList.add("orbita-vote-already-voted");
52-
object.classList.remove("orbita-vote-can-vote");
53-
}
54-
}
26+
async function upVote(postId, object) {
27+
const url = `${orbitaApi.restURL}orbitaApi/v1/likes`;
28+
const formData = new URLSearchParams();
29+
formData.append('post_id', postId);
30+
31+
const headers = {
32+
'Content-Type': 'application/x-www-form-urlencoded',
33+
'X-WP-Nonce': orbitaApi.restNonce,
5534
};
35+
36+
try {
37+
const response = await fetch(url, {
38+
method: 'POST',
39+
headers,
40+
body: formData.toString(),
41+
});
42+
43+
if (!response.ok) {
44+
throw new Error(`HTTP error! status: ${response.status}`);
45+
}
46+
47+
const jsonData = await response.json();
48+
49+
if (jsonData.success) {
50+
const textToUpdate = document.querySelector(
51+
`[data-votes-post-id='${postId}']`,
52+
);
53+
textToUpdate.innerHTML = jsonData.count;
54+
55+
object.classList.add('orbita-vote-already-voted');
56+
object.classList.remove('orbita-vote-can-vote');
57+
}
58+
59+
} catch (error) {
60+
throw new Error('Erro ao enviar voto:', error);
61+
}
5662
}
5763

5864
// Verifica o tamanho da imagem anexada ao post antes de enviar
@@ -100,4 +106,4 @@ function toggleAttachUrl() {
100106

101107
postUrlInput.addEventListener('input', toggleAttachUrl);
102108
postAttachInput.addEventListener('input', toggleAttachUrl);
103-
}
109+
}

0 commit comments

Comments
 (0)