-
Notifications
You must be signed in to change notification settings - Fork 2
/
AJAX.js
52 lines (45 loc) · 1.44 KB
/
AJAX.js
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
52
Asynchronous JAvascript and Xml
-API communications
-by Beumsk
// AJAX GET func
// target URL and callback func as parameters (callback runs if success)
function ajaxGet(url, callback) {
var req = new XMLHttpRequest();
req.open("GET", url);
req.addEventListener("load", function () {
if (req.status >= 200 && req.status < 400) {
// callback with request answer
callback(req.responseText);
} else {
console.error(req.status + " " + req.statusText + " " + url);
}
});
req.addEventListener("error", function () {
console.error("Network error with URL : " + url);
});
req.send(null);
}
// AJAX POST func
// target URL, data to send and callback func as parameters (callback runs if success)
function ajaxPost(url, data, callback, isJson) { // isJson checks if data is json format
var req = new XMLHttpRequest();
req.open("POST", url);
req.addEventListener("load", function () {
if (req.status >= 200 && req.status < 400) {
// callback with request answer
callback(req.responseText);
} else {
console.error(req.status + " " + req.statusText + " " + url);
}
});
req.addEventListener("error", function () {
console.error("Network error with URL : " + url);
});
if (isJson) {
// request content is JSON
req.setRequestHeader("Content-Type", "application/json");
// turns data into JSON before sending
data = JSON.stringify(data);
}
req.send(data);
}