forked from tunapanda/wp-h5p-xapi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwp-h5p-xapi.js
115 lines (94 loc) · 2.5 KB
/
wp-h5p-xapi.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
jQuery(function($) {
var spinnerCount = 0;
/**
* Show the spinner and increase counter.
*/
function showSpinner() {
spinnerCount++;
$("#wp-h5p-xapi-spinner").show();
}
/**
* Decrease the spinner count. Hide if no more spinners.
*/
function hideSpinner() {
spinnerCount--;
if (!spinnerCount)
$("#wp-h5p-xapi-spinner").fadeOut(500);
}
/**
* Show error.
*/
function showError(message, code) {
console.error("Unable to save xAPI statement");
alert("Unable to save result data.\n\nMessage: " + message + "\n" + "Code: " + code);
}
/**
* Post error.
*/
function onXapiPostError(xhr, message, error) {
hideSpinner();
console.log("xapi post error");
console.log(xhr.responseText);
showError(message, xhr.status);
}
/**
* Post success.
*/
function onXapiPostSuccess(res, textStatus, xhr) {
hideSpinner();
if (!res.hasOwnProperty("ok")) {
console.log("xapi post error");
console.log(xhr.responseText);
showError("Got bad response back...", 500);
}
if (!res.ok) {
console.log("xapi post error");
console.log(xhr.responseText);
showError(res.message, res.code);
}
}
/**
* xAPI statement event listener.
*/
function onXapi(event) {
if (!WP_H5P_XAPI_STATEMENT_URL)
return;
showSpinner();
var data = {};
/*console.log("on xapi, statement:");
console.log(JSON.stringify(event.data.statement));*/
if (typeof event.data.statement.context == 'undefined'){
console.log("here, context");
event.data.statement.context = {};
}
if (typeof event.data.statement.context.contextActivities == 'undefined'){
console.log("here, contextActivities");
event.data.statement.context.contextActivities = {};
}
if (typeof event.data.statement.context.contextActivities.grouping == 'undefined'){
console.log("here, grouping");
event.data.statement.context.contextActivities.grouping = [];
}
event.data.statement.context.contextActivities.grouping.push(WP_H5P_XAPI_CONTEXTACTIVITY);
data.statement = JSON.stringify(event.data.statement);
//data.statement = event.data.statement;
$.ajax({
type: "POST",
url: WP_H5P_XAPI_STATEMENT_URL,
data: data,
dataType: "json",
success: onXapiPostSuccess,
error: onXapiPostError
});
}
/**
* Main.
* Create save spinner and register event listener.
*/
$(document).ready(function() {
console.log("ready");
H5P.externalDispatcher.on('xAPI', onXapi);
$("body").append("<div id='wp-h5p-xapi-spinner'>Saving...</div>");
$("#wp-h5p-xapi-spinner").hide();
});
});