Quantcast
Viewing all articles
Browse latest Browse all 6517

New Post: Odd: Can't add columns to a list

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-par's as I've written a grand total of about three things in JavaScript, and have very limited knowledge of SP. But first, some context:

I am a teacher - running the ICT and Computer Science department of a South London Academy - we teach both disciplines to 11-18year 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 dilema: I have 555-ish students needing their homework setting every week, I deliver all my learning resources via the SP 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 JS 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 (I hope - haven't tested that bit as not on the local network!) the file to the relevant document store in the SP server. The teacher then just creats 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's 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.

Wheeee :)
<!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.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;
 
 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 add data!');
                                                insertdata();
                                            }
                                        });
                                    }
                                    else {
                                    // Error creating fields!
                                    alert("Error creating fields!");
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
 }

 function insertdata() {
    var thisUserName = $().SPServices.SPGetCurrentUser({
        fieldName: "Title",
        debug: false
    });
    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);
 }
 
 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++;
                }
            }
        }
    }
  var url = window.location.pathname;
  filename = url.substring(url.lastIndexOf('/')+1);
  filename = filename.substring(0,filename.lastIndexOf('.'));
  $(document).ready(function() {  
    checkiflistexists();
  }); 
 }
 
 function starttime() {
    startseconds = new Date().getTime() / 1000;
 }
 
 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="starttime()">
 <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;"></p>');
    document.write('</div>');
  </script>
  </form>
 </div>
</body>
</html>

Viewing all articles
Browse latest Browse all 6517

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>