grade.js 1.92 KB
Newer Older
1
M.local_asystgrade = {
2
    init: function(Y, js_data) {
3
4
5
        window.gradeData = js_data;
        document.addEventListener('DOMContentLoaded', function() {
            const apiEndpoint = M.cfg.wwwroot + '/local/asystgrade/api.php';
6
7
8
            const maxmark = document.querySelectorAll("input[name$='-maxmark']")[0].value;
            const answerDivs = document.querySelectorAll(".qtype_essay_response");
            const studentAnswers = Array.from(answerDivs).map(element => element.innerText || element.value);
9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
            const gradesDataRequest = {
                referenceAnswer: document.querySelectorAll(".essay .qtext p")[0].innerHTML,
                studentAnswers: studentAnswers
            };

            fetch(apiEndpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(gradesDataRequest)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.grades) {
                        console.log(data.grades);
26
                        updateMarks(data.grades);
27
28
29
30
31
                    } else {
                        console.error('Error in grade response:', data.error);
                    }
                })
                .catch(error => console.error('Error:', error));
32
33

            function updateMarks(grades) {
34
35
                const inputs = document.querySelectorAll("input[name$='_-mark']");

36
                grades.forEach((grade, index) => {
37
                    const predictedGrade = grade.predicted_grade === 'correct' ? maxmark : 0;
38

39
40
                    if (inputs[index]) {
                        inputs[index].value = predictedGrade;
41
                    } else {
42
                        console.error(`No grade input found for index: ${index}`);
43
44
45
46
47
                    }
                });
            }
        });
    }
48
};