-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxhr.js
More file actions
51 lines (44 loc) · 1.24 KB
/
xhr.js
File metadata and controls
51 lines (44 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const objectData = {
name: "Mr. Simon Hembrom",
age: 24,
title: "Web Developer",
sallary: 50000,
phone: "(+880) 17xxxxxxxx",
};
// Varialbes declearation:
const postUrl = "https://jsonplaceholder.typicode.com/posts";
const getUrl = "https://jsonplaceholder.typicode.com/posts/1";
const getButton = document.getElementById("get-button");
const sendButton = document.getElementById("send-button");
// Send the Request func:
const sendRequest = function (method, url, data) {
const promise = new Promise((resolve, reject) => {
// request
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = "json";
xhr.send(data);
// response
xhr.onload = () => {
resolve(xhr.response);
};
});
return promise;
};
// post the data func:
const sendData = function () {
const postData = JSON.stringify(objectData);
sendRequest("POST", postUrl, postData).then((responseData) => {
console.log(responseData);
});
};
// Get the data func:
const getData = () => {
sendRequest("GET", getUrl).then((responseData) => {
console.log(responseData);
});
};
// Add eventListener:
getButton.addEventListener("click", getData);
sendButton.addEventListener("click", sendData);