SPServices Stories #6 – Custom Quizzing System

This entry is part 6 of 21 in the series SPServices Stories

Introduction

Many times, SPServices Stories play out on the field of the Codeplex Discussions. As someone posts questions about how to build some of the components of their solution, the overall plan comes into focus.

Over the last week or so, I’ve been helping Oli Howson (@Mr_Howson) in the discussions here and here. As the bits and pieces came to together for me, I thought that Oli’s work in progress would make a great SPServices Story, especially since he took the trouble to write up what he was trying to accomplish in the discussion thread.

Oli’s project is in process, and it’s certainly possible that he will make changes from here. However, I thought it would be useful to post things “as-is” so that everyone could see how he’s going about it. If he makes any significant changes, we’ll try to post them back as well.

If you have any comments for Oli about how you might do things differently, I’m sure he’d be interested. I know I would be.

Oli’s entire bespoke page is shown below, so you get to see the markup, the script, everything.

Custom Quizzing System

I am a teacher – running the ICT and Computer Science department of a South London Academy – we teach both disciplines to 11-18 year olds. For key-stage 3 (Y7, 8 and 9) we have for the last few years set homework on our VLE (Virtual Learning Environment) which had a built-in testing system. Due to that being about the only part of the VLE that wasn’t naff, it was recently retired and a new SharePoint system brought in. It’s got a few bespoke bits, and I am not an admin. Now I’m faced with the dilemma: I have 555-ish students needing their homework setting every week, I deliver all my learning resources via the SharePoint system, but there is no built-in quizzing system. Yes – there are surveys, but they don’t mark and have their own foibles. So I built this JavaScript-based quizzing system.

Methodology

The teacher in charge of setting homework that week creates a multiple-choice quiz on a stand-alone piece of client software I wrote in Delphi. This then creates an array string which it pastes into the quiz template (with a relevant name) and copies the file to the relevant document store in the SharePoint server. The teacher then just creates a link from the homework page to the relevant quiz, and when the kids hit the quiz the results go into the relevant list (created with the same name as the quiz). The difficult bit was making sure that the list was created the first time the quiz is run. The idea is the teacher hits the quiz once the link is up to make sure it has worked. When they submit, it creates the list, adds the columns, and updates the view. The second time it tests if the list exists (it does now!) and just inserts their score, which it also shows to the kids and then closes the window.

Well, I think I’m there! I’m going to get this beta tested by a group of Year 9 students tomorrow, but I’ll put the code below for reference to anyone that might find it interesting. I’m sure I’ve made loads of faux-pas as I’ve written a grand total of about three things in JavaScript, and have very limited knowledge of SharePoint.

Wheeee :)

[important]Code update with Oli’s changes in version 1.1.0 on 2013-02-14[/important]

<!doctype html>

<html lang="en">
<head>
 <meta charset="utf-8" />
 <title>jQuery UI Tabs - Default functionality</title>
 <link rel="stylesheet" href="/mertonshared/computerstudies/homework/Documents/includes/jquery-ui.css" />
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery-1.8.1.js"></script>
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery-ui.js"></script>
 <script language="javascript" src="/mertonshared/computerstudies/homework/Documents/includes/jquery.SPServices-0.7.2.js" type="text/javascript"></script>
 <script>
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 // Quizzer v1.0.2                                                                                //
 // Change Log:                                                                                   //
 //  - 1.1.0 Added check whether user has completed before - one try only. Reordered some actions //
 //          Added permissions setting when list is being created. Changed submit button value.   //
 //  - 1.0.2 Removed some pointless alerts for ordinary users, reenabled windows.close(), added   //
 //           some useful comments.                                                               //
 //  - 1.0.1 Added view change to show all fields                                                 //
 // Currently available:                                                                          //
 //  - Multiple choice                                                                            //
 //  - Unlimited questions                                                                        //
 //  - Four options per question                                                                  //
 // Future Plans                                                                                  //
 //  - Varying number of options per question                                                     //
 //  - Missing word completion                                                                    //
 //  - Include YouTube clip                                                                       //
 ///////////////////////////////////////////////////////////////////////////////////////////////////

 var startseconds;
 var filename;
 var score;
 var thisUserName;
 var previouslytried;

 function checkiflistexists() {
    //alert('checking existance of list: '+filename);
    $().SPServices ({
        operation: "GetList",
        listName:  filename,
        completefunc: function (xData, Status) {
                //tp1 = xData.responseText;
                //alert(tp1);
                //alert(Status);
                if (Status == 'success') {
                    //alert ('Exists - dont create - just insert data');
                    insertdata();
                }
                else {
                    alert('Dont exist');
                    $().SPServices({
                        operation: "AddList",
                        listName: filename,
                        description: "List created for quiz: "+filename,
                        templateID: 100,
                        completefunc: function (xData, Status) {
                            alert('Trying to create list');
                            alert(Status);
                            alert('Now add fields');
                            var nfields = "<Fields><Method ID='1'><Field Type='Text' DisplayName='Score' ResultType='Text'></Field></Method><Method ID='2'><Field Type='Text' DisplayName='TimeTaken' ResultsType='Text'></Field></Method><Method ID='3'><Field Type='Text' DisplayName='CompletedOn' ResultsType='Text'></Field></Method></Fields>";
                            $().SPServices({
                                operation: 'UpdateList',
                                listName: filename,
                                newFields: nfields,
                                completefunc: function(xData, Status) {
                                    tp1 = xData.responseText;
                                    tp4 = tp1.indexOf("errorstring");
                                    if (tp4 < 0) {
                                        alert("Fields created! - Update View");
                                        var viewname = "";
                                        $().SPServices({
                                            operation: "GetViewCollection",
                                            async: false,
                                            listName: filename,
                                            completefunc: function (xData, Status) {
                                                alert('Complete Func - GewViewCollection');
                                                $(xData.responseXML).find("[nodeName='View']").each(function() {
                                                    var viewdisplayname = $(this).attr("DisplayName");
                                                    if (viewdisplayname=="AllItems") {
                                                        viewname = $(this).attr("Name");
                                                        return false;
                                                    }
                                                });
                                            }
                                        });
                                        alert('Ok - done GetViewCollection - now update the view');
                                        var viewfields = "<ViewFields><FieldRef Name=\"Title\" /><FieldRef Name=\"Score\" /><FieldRef Name=\"TimeTaken\" /><FieldRef Name=\"CompletedOn\" /></ViewFields>";
                                        $().SPServices({
                                            operation: 'UpdateView',
                                            async: false,
                                            listName: filename,
                                            viewName: viewname,
                                            viewFields: viewfields,
                                            completefunc: function(xData, Status) {
                                                alert('Trying to update view');
                                                alert(Status);
                                                alert('Updated view - now update permissions');
                                                //insertdata();
                                                $().SPServices({
                                                    operation: 'AddPermission',
                                                    objectType: 'List',
                                                    objectName: filename,
                                                    permissionIdentifier: "HARRISNET\\ham-grp-students",
                                                    permissionType: 'user',
                                                    permissionMask: 1011028719,
                                                    completefunc: function(xData, Status) {
                                                        alert('Trying to update permissions');
                                                        alert(Status);
                                                        alert(xData.responseXML.xml);
                                                        alert('Done... hopefully! - better insert the data!');
                                                        insertdata();
                                                    }
                                                });
                                            }
                                        });
                                    }
                                    else {
                                    // Error creating fields!
                                    alert("Error creating fields!");
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
 }

 function insertdata() {
    var endseconds = new Date().getTime() / 1000;
    endseconds = endseconds - startseconds;
    var d = new Date();
    var dd = d.toDateString();
    var dt = d.toTimeString();
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: filename,
        valuepairs: [["Title", thisUserName],["Score",score],["TimeTaken",Math.round(endseconds).toString()+" seconds"],["CompletedOn",dd+" "+dt]],
        completefunc: function (xData, Status) {
            //alert('Trying to add data');
            if (Status == 'success') {
                //inserted();
            }
            else {
                alert(Status+' : There was a problem inserting your score into the database. Please notify Mr Howson!');
                //inserted();
            }
        }
    });
    alert('You achieved a score of '+score);
    window.close();
 }

 function checkanswers() {
    var form = document.getElementById('answers');
    score = 0;
    for (var i = 0; i < form.elements.length; i++ ) {
        if (form.elements[i].type == 'radio') {
            if (form.elements[i].checked == true) {
                if (questions[form.elements[i].name.substring(9)-1][questions[form.elements[i].name.substring(9)-1].length-1] == form.elements[i].value)
                {
                 score++;
                }
            }
        }
    }
  $(document).ready(function() {
    checkiflistexists();
  });
 }

 function initialise() {
    var rowcount = 0;
    startseconds = new Date().getTime() / 1000;
    var url = window.location.pathname;
    thisUserName = $().SPServices.SPGetCurrentUser({
        fieldName: "Title",
        debug: false
    });
    filename = url.substring(url.lastIndexOf('/')+1);
    filename = filename.substring(0,filename.lastIndexOf('.'));
    //alert(filename);
    //alert('Getting items');
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: filename,
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Score' /></ViewFields>",
    CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>"+thisUserName+"</Value></Eq></Where></Query>",
    CAMLRowLimit: 1,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        //var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
        score = $(this).attr("ows_Score");
        //$("#tasksUL").append(liHtml);
        rowcount++;
      });
    }
  });
    //alert(rowcount);
    //alert('done');
  if (rowcount > 0) {
   previouslytried = true;
   document.getElementById('tabs').style.visibility = 'hidden';
   alert('Sorry - you have already tried this quiz - one try only!\nLast time you got a '+score);
   window.close();
  }
  else {
   previouslytried = false;
  }
 }

 function inserted() {
    //window.close();
 }

 $(function() {
  $( "#tabs" ).tabs();
 });

 var questions = new Array;
  //The section below should be uncommented when not testing - this will be replaced by the client
  // side application with the questions array.
  [INSERTQUESTIONS]

 //The following questions can be uncommented for testing purposes
 //questions[0] = ['q1','a','b','c',1];
 //questions[1] = ['q2','d','e','f',2];
 //questions[2] = ['q3','g','h','i',3];
 </script>
</head>

<body onload="initialise()">
 <div id="tabs">
  <ul>
   <script language="JavaScript">
    for (var i = 0; i< questions.length; i++)
    {
     document.write('<li><a href="#tabs-'+(i+1)+'">Question '+(i+1)+'</a></li>');
    }
    document.write('<li><a href="#tabs-'+(i+1)+'">Summary</a></li>');
   </script>
  </ul>
   <form name="answers" id="answers">
   <script language="JavaScript">
    for (var i = 0; i < questions.length; i++)
    {
     document.write('<div id="tabs-'+(i+1)+'">');
     document.write(' <p>'+questions[i][0]+'</p>');
     for (var j = 1; j < questions[i].length-1; j++)
     {
      document.write(' <p><input type="radio" name="question-'+(i+1)+'" value="'+j+'">'+questions[i][j]+'<br></p>');
     }
     document.write('</div>');
    }
    document.write('<div id="tabs-'+(i+1)+'">');
    document.write(' <p><input type="submit" onclick="checkanswers(); return false;" value="Submit Homework"></p>');
    document.write('</div>');
  </script>
  </form>
 </div>
</body>
</html>
Series Navigation<< SPServices Stories #5 – Gritter and Sharepoint: Integrate Nifty Notifications in Your Intranet!SPServices Stories #7 – Example Uses of SPServices, JavaScript and SharePoint >>

Similar Posts

2 Comments

  1. Updated on the codeplex site – added permissions setter when creating the list, one try only, and a few tweaks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.