Data Integration

Assignments From Chapter 48

Solutions Assignments DI.1

Assignment DI.1.0

Consider the following:

Example B.111. Colours in JSON

JSON source: https://www.sitepoint.com/colors-json-example/

{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    },
  ]
}

Given the above JSON you must:

  • Check the JSON and correct if you find errors.
  • Use // https://www.w3.org/TR/REC-html40/types.html#h-6.5, and then augment the JSON to hold the 16 basic colours, no more, no less.
  • Create a colour picker consisting of 16 small rectangles coloured with the basic colours, each with a caption of its colour name, and code.
  • Create a test HTML5 page for testing the colour picker.

The objects you might create in JavaScript to represent the colours must use the OLOO object pattern outlined in the previous JavaScript course.

Example Solution Assignment DI.1.0
Example B.112. jsonColor.js
// https://www.w3.org/TR/REC-html40/types.html#h-6.5
let jsonColorsString = `{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#000000"
      }
    },
    {
      "color": "silver",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [192,192,192,1],
        "hex": "#C0C0C0"
      }
    },
    {
      "color": "gray",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [128,128,128,1],
        "hex": "#808080"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#FFFFFF"
      }
    },
    {
      "color": "maroon",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [128,0,0,1],
        "hex": "#800000"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0000"
      }
    },
    {
      "color": "purple",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [128,0,128,1],
        "hex": "#800080"
      }
    },
    {
      "color": "fuchsia",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [255,0,255,1],
        "hex": "#ff00ff"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,128,0,1],
        "hex": "#008000"
      }
    },
    {
      "color": "lime",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#00ff00"
      }
    },
    {
      "color": "olive",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [128,128,0,1],
        "hex": "#808000"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FFFF00"
      }
    },
    {
      "color": "navy",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [0,0,128,1],
        "hex": "#000080"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#0000FF"
      }
    },
    {
      "color": "teal",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [128,0,128,1],
        "hex": "#008080"
      }
    },
    {
      "color": "aqua",
      "category": "value",
      "type": "primary",
      "code": {
        "rgba": [0,255,255,1],
        "hex": "#00FFFF"
      }
    }
  ]
}`;

Example B.113. json10.js
'use strict';
let goto1 = function() {
    let jsonObj = JSON.parse(jsonColorsString);

    let tab = document.createElement('table');
    for(let i = 0; i < jsonObj.colors.length; i++) {
        let row = document.createElement('tr');
        let celll = document.createElement('td');
        celll.setAttribute('id', 'i'+i);
        celll.setAttribute('style', 'background-color: ' + jsonObj.colors[i].code.hex);
        celll.addEventListener('click', function y(ev) {
            console.log(ev.target.id);
            $('a').addEventListener('click', function z(e) {
                console.log(e.target.id);
                $(e.target.id).style.backgroundColor = $(ev.target.id).style.backgroundColor;
            });
        });
        let cellm = document.createElement('td');
        let tnode = document.createTextNode(jsonObj.colors[i].color);
        cellm.appendChild(tnode);
        let cellr = document.createElement('td');
        tnode = document.createTextNode(jsonObj.colors[i].code.hex);
        cellr.appendChild(tnode);
        row.appendChild(celll);
        row.appendChild(cellm);
        row.appendChild(cellr);
        tab.appendChild(row);
    }
    $('ri').appendChild(tab);
}

window.addEventListener('load', goto1);

Example B.114. json10.html
<!doctype html>
<html>
    <head>
        <title>NMLs JSON.1.0 - Colour Picker</title>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <link rel='stylesheet' href='json10.css'/>
        <script src='nQuery.js'></script>
        <script src='jsonColor.js'></script>
        <script src='json10.js'></script>
    </head>
    <body>
        <h1>Color Picker</h1>
        <section id='le'>
            <div id='a'></div>
            <div id='b'></div>
            <div id='c'></div>
        </section>
        <section id='ri'></section>
    </body>
</html>

Check it!


Assignment DI.1.1

Consider the following:

Example B.115. Distance Tables

JSON source, a site for generating test data in many formats. https://www.mockaroo.com/

[
    { "id": 1, "city": "Sortavala", "lat": 61.6487504, "lon": 30.5926449, "country": "Russia" }, 
    { "id": 2, "city": "Yufrus", "lat": "13.45529", "lon": "43.94704", "country": "Yemen" }, 
    { "id": 3, "city": "El Nido", "lat": 11.160632, "lon": 119.3978597, "country": "Philippines" }, 
    { "id": 4, "city": "Wangsi", "lat": 23.7247599, "lon": 108.8076195, "country": "China" }, 
    { "id": 5, "city": "Beiguoyuan", "lat": 36.632873, "lon": 107.288356, "country": "China" }, 
    { "id": 6, "city": "Buurhakaba", "lat": 2.7991084, "lon": 44.0793911, "country": "Somalia" }, 
    { "id": 7, "city": "Alofi", "lat": -19.0553711, "lon": -169.9178709, "country": "Niue" }, 
    { "id": 8, "city": "Bayt ‘Adhāqah", "lat": "15.61576", "lon": "43.70228", "country": "Yemen" }, 
    { "id": 9, "city": "Duru", "lat": 31.269454, "lon": 95.63196, "country": "China" }, 
    { "id": 10, "city": "Ban Huai Thalaeng", "lat": 14.9649534, "lon": 102.6298251, "country": "Thailand" }, 
    { "id": 11, "city": "Oelaba", "lat": -10.7540132, "lon": 122.9104995, "country": "Indonesia" }, 
    { "id": 12, "city": "Sindangan", "lat": 8.3104933, "lon": 122.9938347, "country": "Philippines" }, 
    { "id": 13, "city": "Rukem", "lat": -6.8013457, "lon": 111.4126837, "country": "Indonesia" }, 
    { "id": 14, "city": "Krzczonów", "lat": 49.7371648, "lon": 19.9186389, "country": "Poland" }, 
    { "id": 15, "city": "Otrado-Kubanskoye", "lat": 45.245678, "lon": 40.8360129, "country": "Russia" }, 
    { "id": 16, "city": "La Cruz", "lat": -34.3998126, "lon": -58.6057651, "country": "Argentina" }, 
    { "id": 17, "city": "Mrkonjić Grad", "lat": 44.4186959, "lon": 17.0868199, "country": "Bosnia and Herzegovina" }, 
    { "id": 18, "city": "Mehar", "lat": 27.1668637, "lon": 67.8288595, "country": "Pakistan" }, 
    { "id": 19, "city": "Mizur", "lat": 42.8509219, "lon": 44.0546008, "country": "Russia" }, 
    { "id": 20, "city": "Velké Hoštice", "lat": 49.936089, "lon": 17.9738035, "country": "Czech Republic" }
]

The fields lat, and lon are latitude, and longitude, respectively.


The assignment is to create a distance table such that it displays the distance from any city to all the other 19 cities. Distances are to be calculated as distances on a great circle through two cities. You have solved a previous assignment calculating distances this way. Find your solution to the section called “Assignment Func.1.4” for calculation details

The objects you create in JavaScript to represent the cities must use the OLOO object pattern outlined in the previous JavaScript course.

Example Solution Assignment DI.1.1
Example B.116. jsonCities.js
// https://www.w3.org/TR/REC-html40/types.html#h-6.5
let jsonCitiesString = `[
    { "id": 0, "city": "", "lat": 0, "lon": 0, "country": "GB" }, 
    { "id": 1, "city": "Sortavala", "lat": 61.6487504, "lon": 30.5926449, "country": "Russia" }, 
    { "id": 2, "city": "Yufrus", "lat": "13.45529", "lon": "43.94704", "country": "Yemen" }, 
    { "id": 3, "city": "El Nido", "lat": 11.160632, "lon": 119.3978597, "country": "Philippines" }, 
    { "id": 4, "city": "Wangsi", "lat": 23.7247599, "lon": 108.8076195, "country": "China" }, 
    { "id": 5, "city": "Beiguoyuan", "lat": 36.632873, "lon": 107.288356, "country": "China" }, 
    { "id": 6, "city": "Buurhakaba", "lat": 2.7991084, "lon": 44.0793911, "country": "Somalia" }, 
    { "id": 7, "city": "Alofi", "lat": -19.0553711, "lon": -169.9178709, "country": "Niue" }, 
    { "id": 8, "city": "Bayt ‘Adhāqah", "lat": "15.61576", "lon": "43.70228", "country": "Yemen" }, 
    { "id": 9, "city": "Duru", "lat": 31.269454, "lon": 95.63196, "country": "China" }, 
    { "id": 10, "city": "Ban Huai Thalaeng", "lat": 14.9649534, "lon": 102.6298251, "country": "Thailand" }, 
    { "id": 11, "city": "Oelaba", "lat": -10.7540132, "lon": 122.9104995, "country": "Indonesia" }, 
    { "id": 12, "city": "Sindangan", "lat": 8.3104933, "lon": 122.9938347, "country": "Philippines" }, 
    { "id": 13, "city": "Rukem", "lat": -6.8013457, "lon": 111.4126837, "country": "Indonesia" }, 
    { "id": 14, "city": "Krzczonów", "lat": 49.7371648, "lon": 19.9186389, "country": "Poland" }, 
    { "id": 15, "city": "Otrado-Kubanskoye", "lat": 45.245678, "lon": 40.8360129, "country": "Russia" }, 
    { "id": 16, "city": "La Cruz", "lat": -34.3998126, "lon": -58.6057651, "country": "Argentina" }, 
    { "id": 17, "city": "Mrkonjić Grad", "lat": 44.4186959, "lon": 17.0868199, "country": "Bosnia and Herzegovina" }, 
    { "id": 18, "city": "Mehar", "lat": 27.1668637, "lon": 67.8288595, "country": "Pakistan" }, 
    { "id": 19, "city": "Mizur", "lat": 42.8509219, "lon": 44.0546008, "country": "Russia" }, 
    { "id": 20, "city": "Velké Hoštice", "lat": 49.936089, "lon": 17.9738035, "country": "Czech Republic" }
]`;

Example B.117. json11.js
'use strict';
let gotor = function() {
    var jsonArr = JSON.parse(jsonCitiesString);

    var tab = document.createElement('table');
    var row = document.createElement('tr');
    var celll;
    var tnode;
    let i;
    for (i = 0; i < jsonArr.length; i++) {
        celll = document.createElement('td');
        tnode = document.createTextNode(jsonArr[i].city);
        celll.appendChild(tnode);
        row.appendChild(celll);
    }
    tab.appendChild(row);

    for (i = 1; i < jsonArr.length; i++) {
        let j;
        row = document.createElement('tr');
        for (j = 0; j < jsonArr.length; j++) {
            celll = document.createElement('td');
            if (j === 0) {
                tnode = document.createTextNode(jsonArr[i].city);
            } else {
                let x = sphDist(jsonArr[i].lat, jsonArr[i].lon, jsonArr[j].lat, jsonArr[j].lon);
                tnode = document.createTextNode(Math.round(x, 0));
            }

            if (i === j) {
                celll.setAttribute('style', 'background-color: #333333');
            }

            celll.appendChild(tnode);
            row.appendChild(celll);
        }
        tab.appendChild(row);
    }
    $('dt').appendChild(tab);
    console.log(sphDist(54.323924, 10.1315442, 55.9436722, 9.1282005));
    console.log(sphDist(55.9436722, 9.1282005, 54.323924, 10.1315442));
}

var deg2rad = function(deg) {
    return deg * (Math.PI / 180);
}
var sphDist = function(lat0, lon0, lat1, lon1) {
        const R = 6371.01;
        let phi0 = deg2rad(lat0);
        let lambda0 = deg2rad(lon0);
        let phi1 = deg2rad(lat1);
        let lambda1 = deg2rad(lon1);
        let cosdelta = Math.sin(phi0) * Math.sin(phi1) 
            + Math.cos(phi0) * Math.cos(phi1) * Math.cos(lambda0 - lambda1);
        let raddelta = Math.acos(cosdelta);
        return R * raddelta;
}
window.addEventListener('load', gotor);

Example B.118. json11.html
<!doctype html>
<html>
    <head>
        <title>NMLs JSON.1.1 - Distances for Crows</title>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <link rel='stylesheet' href='json11.css'/>
        <script src='nQuery.js'></script>
        <script src='jsonCities.js'></script>
        <script src='json11.js'></script>
    </head>
    <body>
        <h1>Distances for Crows</h1>
        <section id='dt'></section>
    </body>
</html>

Check it!


Assignment DI.1.2

Consider the following:

Example B.119. The Languages of the World

JSON source may be downloaded from: https://gitlab.com/arosano/worldlanguages.git . The listing hereunder is a fragment prettified for easy reading.

[
    {"speakers":"5459","language":"Dutch","countrycode":"ABW"},
    {"speakers":"9785","language":"English","countrycode":"ABW"},
    {"speakers":"79001","language":"Papiamento","countrycode":"ABW"},
    {"speakers":"7622","language":"Spanish","countrycode":"ABW"},
    {"speakers":"204480","language":"Balochi","countrycode":"AFG"},
    ...
]

The JSON file holds 987 objects of countrylanguage information. Your assignment is to calculate how many speaks each language in the world. When that is done, you must print them on an HTML5 page, numbered, forty (40) at a time, such that the user may click his way to viewing the following forty.

The objects you create in JavaScript to represent the countrylanguage combinations must use the OLOO object pattern outlined in the previous JavaScript course.

Example Solution Assignment DI.1.0
Example B.120. Ajax.js
'use strict';
/*
 * use of getFile
 * requires 'callBack(x)' to be defined in app.
 */
let Ajax = {
    init() {
        this.respObj = null;
        this.ajaxobj = false;
        try {
            this.ajaxobj = new XMLHttpRequest();
        } catch(err) {
            window.alert(err.message + " Get yourself a browser ;)");
        }
    },
    
    getFile(filename) {
        try {
            this.ajaxobj.addEventListener('load', function(ev) {    
                        if (ev.target.readyState === 4) {
                            if (ev.target.status === 200) {
                                // it was a load event, ie successful return from server
                                this.respObj = ev.target.responseText;
                                callBack(this.respObj);
                            }
                        }
                    });
            this.ajaxobj.open("GET", filename);
            this.ajaxobj.send("");
        } catch(err) {
            alert(err.message + 'WTF');
        } 
    }
}

Example B.121. json10.js
'use strict';

var callBack = function(txt) {
    let ll = {
        init(lang, spk) {
            this.lang = lang;
            this.spk = Number(spk);
        }
    };
    
    let myJson = JSON.parse(txt);
    let lang;
    let arr = [];
    for (lang of myJson) {
        let found = false;
        let i;
        let lobj = Object.create(ll);
        lobj.init(lang.language, lang.speakers);
        for (i = 0; i < arr.length; i++) {
            if (lobj.lang === arr[i].lang) {
                arr[i].spk += lobj.spk;
                found = true;
            }
        }
        if (!found) {
            arr[i] = lobj;
        }
    }
    
    // sort by number of speakers
    arr.sort(function (a, b) {
        return b.spk - a.spk;
    });
    
    let start = 0;
    let pageHeight = 20;

    display(arr, start, pageHeight);
    
    $('btn2').addEventListener('click', function x() {
        clear();
        start += pageHeight;
        display(arr, start, pageHeight);
    });
    $('btn1').addEventListener('auxclick', function y() {
        clear();
        start -= pageHeight;
        display(arr, start, pageHeight);
    });
}

let clear = function () {
    while ($('dt').firstChild) {        // Removing all children from an element
        $('dt').removeChild($('dt').firstChild);
    }
}

let display = function(arr, start, numRows) {
    let tbl = document.createElement('table');
    let i;
    if (arr.length - start < numRows) {
        start = arr.length - numRows;
    }
    if (start < 0) {
        start = 0;
    }
    for (i = start; i < start+numRows; i++) {
        let rw = document.createElement('tr');
        let td = document.createElement('td');
        td.setAttribute('style', 'text-align: right; width: 2em;');
        let num = document.createTextNode(Number(i+1));
        td.appendChild(num);
        rw.appendChild(td);
        
        td = document.createElement('td');
        let txt = document.createTextNode(arr[i].lang);
        td.appendChild(txt);
        rw.appendChild(td);
        
        td = document.createElement('td');
        td.setAttribute('style', 'text-align: right;');
        num = document.createTextNode(Number(arr[i].spk).toLocaleString());
        td.appendChild(num);
        rw.appendChild(td);
        tbl.appendChild(rw);
    }
    $('dt').appendChild(tbl);
}

let getJSONFile = function(e) {
    let ajax = Object.create(Ajax);
    ajax.init();
    ajax.getFile('../DIAss/languages.json');
}

window.addEventListener('load', getJSONFile);

Example B.122. json10.html
<!doctype html>
<html>
    <head>
        <title>NMLs JSON.1.2 - Languages of the Worlds</title>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <link rel='stylesheet' href='json11.css'/>
        <script src='nQuery.js'></script>
        <script src='Ajax.js'></script>
        <script src='json12.js'></script>
    </head>
    <body>
        <h1>Languages of the Worlds</h1>
        <section id='dt'></section>
        <section>
            <button id='btn1'>&lt;</button>&nbsp;&nbsp;<button id='btn2'>&gt;</button>
        </section>
    </body>
</html>

Check it!


Assignments From Chapter 49

Solutions Assignments DI.2

Model Solution Assignment DI.2.0

Research and answer the following:

  1. Are maxLength, or minLength allowed on optional name/value pairs?
  2. Based on the basics from Chapter 48 JSON has Number, Boolean, Null, String, Object, and Array as object types. Research whether they all apply as types in JSON-schema. Make an example that proves your answer.
  3. Make a JSON-schema for the JSON in the section called “Assignment DI.1.0” and perform validation of the JSON
  4. Make a JSON-schema for the JSON in the section called “Assignment DI.1.1” and perform validation of the JSON
  5. Make a JSON-schema for the JSON in the section called “Assignment DI.1.2” and perform validation of the JSON
Model Solution Assignment DI.2.0

Research and answer the following:

  1. Yes
  2. They all apply. Find examples in the section called “JSON Types”.
  3. {
       "$id": "http://example.com/example.json", 
       "type": "object", 
       "definitions": {}, 
       "$schema": "http://json-schema.org/draft-07/schema#", 
       "properties": {
         "colors": {
           "$id": "/properties/colors", 
           "type": "array", 
           "items": {
             "$id": "/properties/colors/items", 
             "type": "object", 
             "properties": {
               "color": {
                 "$id": "/properties/colors/items/properties/color", 
                 "type": "string", 
                 "title": "The Color Schema ", 
                 "default": "", 
                 "examples": [
                   "black"
                 ]
               }, 
               "category": {
                 "$id": "/properties/colors/items/properties/category", 
                 "type": "string", 
                 "title": "The Category Schema ", 
                 "default": "", 
                 "examples": [
                   "hue"
                 ]
               }, 
               "type": {
                 "$id": "/properties/colors/items/properties/type", 
                 "type": "string", 
                 "title": "The Type Schema ", 
                 "default": "", 
                 "examples": [
                   "primary"
                 ]
               }, 
               "code": {
                 "$id": "/properties/colors/items/properties/code", 
                 "type": "object", 
                 "properties": {
                   "rgba": {
                     "$id": "/properties/colors/items/properties/code/properties/rgba", 
                     "type": "array", 
                     "items": {
                       "$id": "/properties/colors/items/properties/code/properties/rgba/items", 
                       "type": "integer", 
                       "title": "The 0th Schema ", 
                       "default": 0, 
                       "examples": [
                         0, 
                         0, 
                         0, 
                         1
                       ]
                     }
                   }, 
                   "hex": {
                     "$id": "/properties/colors/items/properties/code/properties/hex", 
                     "type": "string", 
                     "title": "The Hex Schema ", 
                     "default": "", 
                     "examples": [
                       "#000000"
                     ]
                   }
                 }
               }
             }
           }
         }
       }
     }
    
    (Student handin from feb 2018.) There seems to be a generator somewhere :)
  4.  {
       "$id": "http://example.com/example.json", 
       "type": "array", 
       "definitions": {}, 
       "$schema": "http://json-schema.org/draft-07/schema#", 
       "items": {
         "$id": "http://example.com/example.json/items", 
         "type": "object", 
         "properties": {
           "id": {
             "$id": "http://example.com/example.json/items/properties/id", 
             "type": "integer", 
             "title": "The Id Schema ", 
             "default": 0, 
             "examples": [
               0
             ]
           }, 
           "city": {
             "$id": "http://example.com/example.json/items/properties/city", 
             "type": "string", 
             "title": "The City Schema ", 
             "default": "", 
             "examples": [
               ""
             ]
           }, 
           "lat": {
             "$id": "http://example.com/example.json/items/properties/lat", 
             "type": "integer", 
             "title": "The Lat Schema ", 
             "default": 0, 
             "examples": [
               0
             ]
           }, 
           "lon": {
             "$id": "http://example.com/example.json/items/properties/lon", 
             "type": "integer", 
             "title": "The Lon Schema ", 
             "default": 0, 
             "examples": [
               0
             ]
           }, 
           "country": {
             "$id": "http://example.com/example.json/items/properties/country", 
             "type": "string", 
             "title": "The Country Schema ", 
             "default": "", 
             "examples": [
               "GB"
             ]
           }
         }
       }
    }
    
    (Student handin from feb 2018.)
  5. {
    "$id": "http://example.com/example.json", 
    "type": "array", 
    "definitions": {}, 
    "$schema": "http://json-schema.org/draft-07/schema#", 
    "items": {
        "$id": "http://example.com/example.json/items", 
        "type": "object", 
        "properties": {
           "speakers": {
             "$id": "http://example.com/example.json/items/properties/speakers", 
             "type": "string", 
             "title": "The Speakers Schema ", 
             "default": "", 
             "examples": [
               "5459"
             ]
           }, 
           "language": {
             "$id": "http://example.com/example.json/items/properties/language", 
             "type": "string", 
             "title": "The Language Schema ", 
             "default": "", 
             "examples": [
               "Dutch"
             ]
           }, 
           "countrycode": {
             "$id": "http://example.com/example.json/items/properties/countrycode", 
             "type": "string", 
             "title": "The Countrycode Schema ", 
             "default": "", 
             "examples": [
               "ABW"
             ]
           }
         }
       }
     }
    
    (Student handin from feb 2018.)
Assignment DI.2.1

Create an AJaX one page application that allows chosing a country from a drop down or as a key in. The page issues an AJaX request to a PHP program reading from the World database. The data must be returned as JSON and displayed by JavaScript. The displayed data must be:

  • Country name
  • Population
  • Capital city
  • Population of capital city
  • All official languages
  • Density of population
  • Head of state
Model Solution Assignment DI.2.1

Løsning: Frederik.

Example B.123. Included file content.php, HTML5 Skeleton
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="index.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>

</body>
</html>

Example B.124. Page index.php

This page generates countriers.json.

<?php
require_once 'db/DbP.inc.php';
require_once 'db/DbH.inc.php';
$dbh = DbH::getDbH();

$sql = "select
country.name AS 'countryName',
country.population AS 'countryPopulation',
city.name 'capitalName',
city.population AS 'cityPopulation',
countrylanguage.language AS 'language',
country.population/country.surfacearea AS 'density',
country.headofstate AS 'headOfState'";
$sql .= " from country";
$sql .= " join city on country.code=city.countrycode";
$sql .= " join countrylanguage on country.code=countrylanguage.countrycode";
$sql .= " group by country.name";
$res = $dbh->query($sql);

$a = array();
while ($out = $res->fetch(PDO::FETCH_ASSOC)) {
    array_push($a, $out);
}

$content = json_encode($a);
file_put_contents('countries.json', $content);

require_once('content.php');
?>

Example B.125. JS Generating Content index.js

After index.php generates the json, this JavaScript reads it via AJaX and formats it onto the page.

createButton = function() {

  let h1 = document.createElement('h1');
  let h1text = document.createTextNode('Counties');
  h1.appendChild(h1text);
  document.body.appendChild(h1);

  let content = document.createElement('select');
  document.body.appendChild(content);
  content.setAttribute('id', 'countries');

  let submit = document.createElement('input');
  document.body.appendChild(submit);
  submit.setAttribute('type', 'submit');
  submit.setAttribute('value', 'Display country');
  submit.setAttribute('id', 'submitButton');
  document.getElementById('submitButton').style.marginTop = "2em";

  let countryInfo = document.createElement('div');
  document.body.appendChild(countryInfo);
  countryInfo.setAttribute('id', 'displayCountry');
}


window.addEventListener('load', createButton);



function loadCountries() {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'countries.json', true);

    xhr.onload = function () {
        if (this.status === 200) {
            let countries = JSON.parse(this.responseText);
            let output = '';
            for (let i in countries)
                output += '<option>'+countries[i].countryName+'</option>';



            document.getElementById('countries').innerHTML = output;
            document.getElementById('countries').style.display = "block";
        }
        else {
            document.getElementById('countries').innerHTML = "Not found";
        }
    }

    xhr.onerror = function () {
        document.getElementById('countries').innerHTML = "Request error";
    }
    xhr.send();
}

countryInfo = function () {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'countries.json', true);

  xhr.onload = function () {
      if (this.status === 200) {
          let countries = JSON.parse(this.responseText);
          let output = "";
          for(let i in countries)
              output += "<ul>" +
                  "<li><b>Country Name: </b> "+countries[i].countryName+"</li>" +
                  "<li><b>Country Population: </b>"+countries[i].countryPopulation+"</li>" +
                  "<li><b>Capital Name: </b>"+countries[i].capitalName+"</li>" +
                  "<li><b>Capital Population</b>"+countries[i].cityPopulation+"</li>" +
                  "<li><b>Country Density: </b>"+countries[i].density+"</li>" +
                  "<li><b>Head of State: </b>"+countries[i].headOfState+"</li>" +
                  "</ul>";



          document.getElementById('displayCountry').innerHTML = output;
          document.getElementById('displayCountry').style.display = "block";
      }
      else {
          document.getElementById('countries').innerHTML = "Not found";
      }
  }

  xhr.onerror = function () {
      document.getElementById('countries').innerHTML = "Request error";
  }
  xhr.send();
}

getCountry = function() {
  document.getElementById('submitButton').addEventListener('click', countryInfo);
}

window.addEventListener('load', loadCountries);
window.addEventListener('load', getCountry);

Assignment DI.2.2

Create an AJaX one page application that allows chosing a country, district combination from the World db. The page issues an AJaX request to a PHP program reading from the database. The data must be returned as JSON and displayed by JavaScript. The displayed data must be:

  • Country name
  • District name
  • Cites from district
  • Population of said cities
  • Population of district
  • Population of country
Model Solution Assignment DI.2.2

Assignments From Chapter 50

Solutions Assignments DI.3

Material for Assignments DI.3.0 and DI.3.1

You must use this booksXML2.xml as the book file in the following two assignments. If you wish to validate your book file at any time, there is

Example B.126. validator.php
<?php
            function libxml_display_error($error)
            {
                $return = "<br/>\n";
                switch ($error->level) {
                    case LIBXML_ERR_WARNING:
                        $return .= "<b>Warning $error->code</b>: ";
                        break;
                    case LIBXML_ERR_ERROR:
                        $return .= "<b>Error $error->code</b>: ";
                        break;
                    case LIBXML_ERR_FATAL:
                        $return .= "<b>Fatal Error $error->code</b>: ";
                        break;
                }
              $return .= trim($error->message);
                if ($error->file) {
                    $return .=    " in <b>$error->file</b>";
                }
                $return .= " on line <b>$error->line</b>\n";

                return $return;
            }

            function libxml_display_errors() {
                $errors = libxml_get_errors();
                foreach ($errors as $error) {
                    print libxml_display_error($error);
                }
                libxml_clear_errors();
            }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Validation by XML Schema</title>
    </head>
    <body>
<?php
        libxml_use_internal_errors(true);

        $xml = new DOMDocument();
        $xml->load('booksXML2.xml'); 
        if (!$xml->schemaValidate('booksCanon.xsd')) {
             print '<b>DOMDocument::schemaValidate() Generated Errors!</b>';
             libxml_display_errors();
        } else {
            echo "This document is valid!\n";
        }
?>
    </body>
</html>

to do it. Take a close look at the code. Finally, here's the schema document booksCanon.xsd

Assignment DI.3.0

An administrator is charged with maintaining an XML file of books such that the file may be used as the base for referencing/citing scientific articles.

Create a PHP program displaying the books already in the file. For your convenience use the material previously referred to.

Model Solution Assignment DI.3.0

Drilons solution

Example B.127. The Data books.xml
<?xml version="1.0" encoding="UTF-8"?>
<booksCanon>
  <book ref="Llo08" mycanon="mdu,all">
    <title>Learn How to Build Web Sites the Right Way from Scratch</title>
    <edition>2</edition>
    <authors>
      <author>
        <firstname>Ian</firstname>
        <lastname>Lloyd</lastname>
      </author>
    </authors>
    <publisher>
      <name>SitePoint</name>
      <year>2008</year>
      <place>Collingwood, VIC, Australia</place>
    </publisher>
    <pages>300</pages>
    <isbn></isbn>
    <price>9.73</price>
    <currency>EU&#8364;</currency>
    <comments>
      <comment>1. sem: Chapters 1-7</comment>
    </comments>
  </book>

  <book ref="Shu08" mycanon="mdu">
    <title>Learning ActionScript 3.0</title>
    <edition>2</edition>
    <authors>
      <author>
        <firstname>Rich</firstname>
        <lastname>Shupe</lastname>
      </author>
      <author>
        <firstname>Zevan</firstname>
        <lastname>Rosser</lastname>
      </author>
    </authors>
    <publisher>
      <name>O'Reilly</name>
      <year>2008</year>
      <place>Sebastopol, CA, USA</place>
    </publisher>
    <pages></pages>
    <isbn>978-0596527877</isbn>
    <price>8.73</price>
    <currency>US$</currency>
    <comments>
      <comment>1. sem: Chapters 1-7</comment>
    </comments>
  </book>

  <book ref="Nix09" mycanon="mdu">
    <title>Learning PHP, MySQL, and JavaScript</title>
    <edition>2</edition>
    <authors>
      <author>
        <firstname>Robin</firstname>
        <lastname>Nixon</lastname>
      </author>
    </authors>
    <publisher>
      <name>O'Reilly</name>
      <year>2009</year>
      <place>Sebastopol, CA, USA</place>
    </publisher>
    <pages>120</pages>
    <isbn>123</isbn>
    <price>12.98</price>
    <currency>EU&#8364;</currency>
    <comments>
      <comment>2. sem: Chapters 1-7, 11, 14-17</comment>
      <comment>3. sem: Chapters 8-10</comment>
    </comments>
  </book>

  <book ref="For04" mycanon="mdu,all">
    <title>SQL in 10 Minutes</title>
    <edition>3</edition>
    <authors>
      <author>
        <firstname>Ben</firstname>
        <lastname>Forta</lastname>
      </author>
    </authors>
    <publisher>
      <name>Sams Publishing</name>
      <year>2004</year>
      <place>Indianapolis, IN, USA</place>
    </publisher>
    <pages>100</pages>
    <isbn></isbn>
    <price>120</price>
    <currency>DKR</currency>
    <comments>
      <comment>3. sem: Chapters 1-17</comment>
    </comments>
  </book>

</booksCanon>

Example B.128. The Page index.php
<!DOCTYPE html>
<html>
      <head>
            <meta charset="utf-8">
            <title>Assignment DI.3.0</title>
      </head>
      <body>
            <h1>Assignment DI.3.0 | Drilon Braha</h1>

            <hr>
            <h2>Books in store:</h2>
            <?php
                  $xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
                  // var_dump($xml);
                  foreach ($xml->children() as $key) {

                        echo "title: " . $key->title . "<br>";
                        echo "edition: " . $key->edition . "<br>";
                        echo "author: " . $key->authors->author->firstname . " " . $key->authors->author->lastname . "<br>";
                        echo "publisher: " . $key->publisher->name . " " . $key->publisher->year . " " . $key->publisher->place . "<br>";
                        echo "price: €" . $key->price . "<br>";
                        echo "<br>";
                  }
                  // echo $xml->book[0]->title . "<br>";
            ?>

      </body>
</html>

Do it.


Assignment DI.3.1

Consider the previous assignment. Proper administration is worthless if the administrator cannot add books to the library file.

Create a PHP program that allows the administrator to enter new books into the file. This means a form for entering data, and a backend updating the xml file using SimpleXML functionality as demonstrated in todays lesson. The File must validate after the update according to the schema file provided.

Model Solution Assignment DI.3.1

Drilons solution

Example B.129. The Data books.xml
<?xml version="1.0" encoding="UTF-8"?>
<booksCanon>

<book id="book_id"><title>PHP Learning</title><edition>2</edition><authors><author><firstname>Carlson</firstname><lastname>Bent</lastname></author></authors><publisher><publishername>Kodnings Forlaget</publishername><publisheryear>2019</publisheryear><publisherplace>Copenhagen</publisherplace></publisher><pages>345</pages><price>€ 50</price><currency>€</currency><comments><comment>No comment</comment></comments></book><book id="book_id"><title>test</title><edition>1st</edition><authors><author><firstname>N.</firstname><lastname>Larsen</lastname></author></authors><publisher><publishername>Larsen</publishername><publisheryear>2019</publisheryear><publisherplace>Aarhus</publisherplace></publisher><pages>209</pages><price>€ 12</price><currency>€</currency><comments><comment>test</comment></comments></book><book id="book_id"><title>PHP in 10 minutes</title><edition>99th</edition><authors><author><firstname>Niels</firstname><lastname>Larsen</lastname></author></authors><publisher><publishername>Larsen og co</publishername><publisheryear>2019</publisheryear><publisherplace>Aarhus</publisherplace></publisher><pages>129</pages><price>$ 129</price><currency>$</currency><comments><comment>testudgave</comment></comments></book></booksCanon>

Example B.130. The Display view.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
      <head>
            <meta charset="utf-8">
            <title>Assignment DI.3.1 | View</title>
            <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      </head>

      <body>
            <div class="container">
                  <div class="row">
                        <div class="col-lg-12">
                              <h1>Assignment DI.3.1 | Drilon Braha</h1>
                              <hr>
                        </div>
                  </div>

                  <div class="row">
                        <div class="col-lg-6">
                              <div class="bg-info text-center mb-2">
                                    <a href="index.php" class="text-white"><?php echo "< " ?>Add Books</a>
                              </div>
                              <div class="bg-dark">
                                    <h2 class="text-white p-2">Books in store</h2>
                              </div>
                              <div class="bg-light p-2">
                                    <?php
                                          $xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");

                                          foreach ($xml->children() as $key) {
                                                echo "<h3>title: " . $key->title . "</h3>";
                                                echo "edition: " . $key->edition . "<br>";
                                                echo "author: " . $key->authors->author->firstname . " " . $key->authors->author->lastname . "<br>";
                                                echo "publisher: " . $key->publisher->publishername . " " . $key->publisher->publisheryear . " " . $key->publisher->publisherplace . "<br>";
                                                echo "pages: " . $key->pages . "<br>";
                                                echo "price: " . $key->price . "<br>";
                                                echo "comments: " . $key->comments->comment . "<br>";
                                                echo "<hr>";
                                                echo "<br>";
                                          }
                                    ?>
                              </div>
                        </div>
                  </div>
            </div>

            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
      </body>
</html>

Example B.131. The Page index.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
      <head>
            <meta charset="utf-8">
            <title>Assignment DI.3.1</title>
            <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
      </head>
      <body>
            <div class="container">
                  <div class="row">
                        <div class="col-lg-12">
                              <h1>Assignment DI.3.1 | Drilon Braha</h1>
                              <hr>
                        </div>
                  </div>
            </div>

            <?php
                  if (isset($_REQUEST['ok'])) {
                        $xml = new DOMDocument("1.0", "UTF-8");
                        $xml->load("books.xml");

                        $rootTag = $xml->getElementsByTagName("booksCanon")->item(0);
                        $dataTag = $xml->createElement("book");
                        $bookAttribute = $xml->createAttribute("id");
                        $bookAttribute->value = "book_id";
                        $dataTag->appendChild($bookAttribute);
                        $authorsTag = $xml->createElement("authors");
                        $authorTag = $xml->createElement("author");
                        $publisherTag = $xml->createElement("publisher");
                        $commentsTag = $xml->createElement("comments");

                        $titleTag = $xml->createElement("title", $_REQUEST['title']);
                        $editionTag = $xml->createElement("edition", $_REQUEST['edition']);
                        $firstnameTag = $xml->createElement("firstname", $_REQUEST['firstname']);
                        $lastnameTag = $xml->createElement("lastname", $_REQUEST['lastname']);
                        $publishernameTag = $xml->createElement("publishername", $_REQUEST['publishername']);
                        $publisheryearTag = $xml->createElement("publisheryear", $_REQUEST['publisheryear']);
                        $publisherplaceTag = $xml->createElement("publisherplace", $_REQUEST['publisherplace']);
                        $pagesTag = $xml->createElement("pages", $_REQUEST['pages']);
                        $priceTag = $xml->createElement("price", ($_REQUEST['currency'] . " " . $_REQUEST['price']));
                        $currencyTag = $xml->createElement("currency", ($_REQUEST['currency']));
                        $commentTag = $xml->createElement("comment", $_REQUEST['comment']);

                        $dataTag->appendChild($titleTag);
                        $dataTag->appendChild($editionTag);

                        $rootTag->appendChild($dataTag);
                        $dataTag->appendChild($authorsTag);
                        $dataTag->appendChild($publisherTag);

                        $authorsTag->appendChild($authorTag);
                        $authorTag->appendChild($firstnameTag);
                        $authorTag->appendChild($lastnameTag);

                        $publisherTag->appendChild($publishernameTag);
                        $publisherTag->appendChild($publisheryearTag);
                        $publisherTag->appendChild($publisherplaceTag);

                        $dataTag->appendChild($pagesTag);
                        $dataTag->appendChild($priceTag);
                        $dataTag->appendChild($currencyTag);

                        $dataTag->appendChild($commentsTag);
                        $commentsTag->appendChild($commentTag);
                        $xml->save("books.xml");
                  }
            ?>

            <div class="container">
                  <div class="row">
                        <div class="col-lg-6">
                              <div class="bg-dark">
                                    <h2 class="text-white p-2">Add books</h2>
                              </div>
                              <form class="" action="index.php" method="post">
                                    <div class="form-group">
                                          <label for="title">title</label>
                                          <input type="text" name="title" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="edition">edition</label>
                                          <input type="text" name="edition" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="firstname">firstname</label>
                                          <input type="text" name="firstname" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="lastname">lastname</label>
                                          <input type="text" name="lastname" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="publishername">publishername</label>
                                          <input type="text" name="publishername" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="publisheryear">publisheryear</label>
                                          <input type="text" name="publisheryear" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="publisherplace">publisherplace</label>
                                          <input type="text" name="publisherplace" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="pages">pages</label>
                                          <input type="text" name="pages" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="price">price</label>
                                          <input type="text" name="price" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <label for="currency">currency</label>
                                          <select name="currency" class="form-control form-control-sm" id="exampleFormControlSelect1" required>
                                                <option value="">None</option>
                                                <option value="&#8364;">EU &#8364;</option>
                                                <option value="&#163;">UK &#163;</option>
                                                <option value="&#36;">USD &#36;</option>
                                          </select>
                                    </div>
                                    <div class="form-group">
                                          <label for="comment">comment</label>
                                          <input type="text" name="comment" value="" class="form-control form-control-sm" required>
                                    </div>
                                    <div class="form-group">
                                          <input type="submit" name="ok" value="Tilføj" class="btn btn-primary" required>
                                    </div>
                              </form>
                        </div>
                        <div class="col-lg-4 offset-lg-2">
                              <div class="bg-info text-center">
                                    <a href="view.php" class="text-white">View books</a>
                              </div>
                              <div class="bg-info text-center mt-2">
                                    <a href="books.xml" class="text-white">View XML Tree Structure</a>
                              </div>
                        </div>
                  </div>
            </div>

            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
      </body>
</html>

Do it.