-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax-utils.js
73 lines (58 loc) · 1.6 KB
/
ajax-utils.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
(function (global) {
// Set up a namespace for our utility
var ajaxUtils = {};
// Returns an HTTP request object
function getRequestObject() {
if (window.XMLHttpRequest) {
return (new XMLHttpRequest());
}
else if (window.ActiveXObject) {
// For very old IE browsers (optional)
return (new ActiveXObject("Microsoft.XMLHTTP"));
}
else {
global.alert("Ajax is not supported!");
return(null);
}
}
// Makes an Ajax GET request to 'requestUrl'
ajaxUtils.sendGetRequest =
function(requestUrl, responseHandler, isJsonResponse) {
var request = getRequestObject();
// console.log(requestUrl);
request.onreadystatechange =
function() {
handleResponse(request,
responseHandler,
isJsonResponse);
};
// open request - true for asynch...
request.open("GET", requestUrl, true);
// sends...
request.send(null); // for POST only
};
// Only calls user provided 'responseHandler'
// function if response is ready
// and not an error
// good if ==4 and status ==200
function handleResponse(request,
responseHandler,
isJsonResponse) {
if ((request.readyState == 4) &&
(request.status == 200)) {
// Default to isJsonResponse = true
if (isJsonResponse == undefined) {
isJsonResponse = true;
}
if (isJsonResponse) {
responseHandler(JSON.parse(request.responseText));
}
else {
responseHandler(request.responseText);
}
}
}
// Expose utility to the global object
global.$ajaxUtils = ajaxUtils;
})(window);