Untangling the web10

Preview:

Citation preview

UNTANGLING THE WEBClass 10 – deeper into bluemix and databases

AGENDA• Homework review

• Additional discussion of extra homework• Javascript topics

• JSON• Server side and client side JS• Routes and node.js

• Bluemix• Setting up a bluemix application• Using bluemix services

• Project work• Check to make sure where folks are hosting• Work on issues that are coming up

• Final homework!!

REVIEW OF HOMEWORK #8• There were two hard parts in this

• Silent errors when database calls were done incorrectly• Understanding the calling conventions in WebSQL

• A look at the WebSQL dashboard in google developer console• A deeper look at transact SQL statements

TRANSACT SQL STEPS TO A WEBSQL APP

• A database must have a name• var mydb = openDatabase("cars_db", "0.1", "A Database of Cars I Like",

1024 * 1024);• A table must be created

• t.executeSql("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY ASC, make TEXT, model TEXT)");

• Put things into the table• t.executeSql("INSERT INTO cars (make, model) VALUES (?, ?)", [make,

model]);• Pull things out of the table

• t.executeSql("SELECT * FROM cars", [], updateCarList);

HOW ARE RESULTS RETURNED?• As JSON!!

• You’ve been using JSON – javascript object notation

• Now it’s time to discuss some specifics of it

UPDATE CAR LIST• function updateCarList(transaction, results) {• console.log(transaction);• console.log(results);• //initialise the listitems variable• var listitems = "";• //get the car list holder ul• var listholder = document.getElementById("carlist");

• //clear cars list ul• listholder.innerHTML = "";

UPDATE CAR LIST• var i;• //Iterate through the results• for (i = 0; i < results.rows.length; i++) {• //Get the current row• var row = results.rows.item(i);

• listholder.innerHTML += "<li>" + row.make + " - " + row.model + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)";

• }

• }

NODEJS AND QUERY RESPONSE• App.get pattern

BLUEMIX• We’re going to take the hello world example and extend it into some new

functionality• First, clone the demo application from my github, or better yet fork it to

yours so that you can make changes and then clone it from there• https://github.com/derekja/bluemix_demo

• First pull from my earlier checkin so that you see it on WebSQL• git checkout f207e7b

MODIFY THE MANIFEST SO THAT YOU CAN DEPLOY IT

• Edit manifest.yml to have your name in it so that it is unique• applications:• - name: bluemix-demo-derekja• host: bluemix-demo-derekja• memory: 128M

• Save those changes

RUN LOCALLY• In a git bash terminal…

• Npm install to install all the dependencies

• Npm start to start a local web werver

• Now open a web browser to http://localhost:8080 and see your page

• In the bash terminal press control-c to close the local web server• Or simply open a new terminal if you want to keep your webserver running

DEPLOY TO BLUEMIX• In a git bash terminal…

• “cf push” to push it up to your bluemix account• This presumes that you have set up cloud foundry as we did last week and

that you have modified the manifest so that bluemix creates a new route for this app

• Wait a couple minutes until the push completes and then open the route in your web browser, for instance mine is at http://bluemix-demo-derekja.mybluemix.net

LOOK AT YOUR BLUEMIX DASHBOARD

ADD A SQL SERVER

MOVE THE CARS EXAMPLE TO BLUEMIX ON WEBSQL

• In the public directory, create index.js and index.css files• In the index.html file copy the contents of the cars fiddle html into the

body in place of the <h1> tag that was there. This fiddle is at https://jsfiddle.net/m5rh3a83/1/

• In the index.js file, copy the contents of the js section of the fiddle

• In the index.css file, copy the contents of the css section of the fiddle

POINT TO THE NEW FILES• You’ll need two new lines in the head of the index.html

• <script src="index.js"></script>• <link rel="stylesheet" type="text/css" href="index.css">

• This tells your index.html file where to find the javascript and css

RUN IT LOCALLY THEN PUSH IT TO THE SERVER

• Npm start in a git bash window and point your browser to http://localhost:8080

• The do your “cf push” again to push it to the server

• Check out that the server is working (give it time to complete)

NOW WE’LL CHANGE TO USE A REMOTE SQL SERVER

• First, let’s connect to the server and set up the database

• We’ll use MySQLWorkbench for that, an open source database tool

• http://dev.mysql.com/downloads/workbench/

• (sorry, you’ll have to create an oracle account. Needs a real email address but the rest can be fake)

ONLY INSTALL WORKBENCH!

POINT THE WORKBENCH TO YOUR DATABASE

POINT THE WORKBENCH TO YOUR DATABASE

POINT THE WORKBENCH TO YOUR DATABASE

• Test connection

• Store password in vault

CREATE A NEW TABLE AND FIELDS

SEE THE TABLE!

PUT THE DATABASE CONNECTION INTO YOUR

APPLICATION• In a git bash window, install the “mysql” nodejs plugin

• Save it to the package.json

• “npm install –save mysql”

LOOK AT THE CLEARDB EXAMPLE

• CAN NOW SYNC TO THE LATEST CHECKIN• git checkout eaa30bd

• Look at server.js

LOOK AT HOW WE GET DATA INTO THE DATABASE

• app.get("/add", function(request, response){• var id = null;• var make = request.query.make;• var model = request.query.model;• var queryStr = "INSERT INTO cars (cars.key,cars.name,cars.model) VALUES ('"+id+"','"+make+"','"+model+"')";

• response.writeHead(200, {"Content-Type": "text/plain"})• console.log(queryStr);

• clearDBconnection.query(queryStr, function(err, rows, fields) {• if (err) throw err;• });

• response.end("added!\n");• })

ON THE CLIENT SIDE• //get the values of the make and model text inputs• var make = document.getElementById("carmake").value;• var model = document.getElementById("carmodel").value;

• var xmlhttp = new XMLHttpRequest();• var reqStr = "/add?make="+make+"&model="+model;• xmlhttp.onreadystatechange=function() {• if (xmlhttp.readyState==4 && xmlhttp.status==200) {• var response = xmlhttp.responseText; //if you need to do something with the returned value• }• }

• xmlhttp.open("GET",reqStr,true);• xmlhttp.send();

• • setTimeout(outputCars, 2000);

CALLBACKS FOR GETTING DATA• function getList(queryStr, callback) {

• clearDBconnection.query(queryStr, function(err, rows, fields) {• if (err) throw err;• callback(rows)• });

• }

GETTING DATA OUT OF THE DATABASE

• app.get("/carList", function(request, response){• var id = request.query.id;• var queryStr = "SELECT * from cars";• var rowsResponse = null;• response.writeHead(200, {"Content-Type": "text/plain"})• console.log(queryStr);• getList(queryStr, function(rows) {var objs = [];• for (var i = 0;i < rows.length; i++) {• objs.push({key: rows[i].key, name: rows[i].name, model: rows[i].model});• }• rowsResponse = JSON.stringify(objs);• console.log(rowsResponse);• response.end(JSON.stringify(objs)); • })

PROJECT DISCUSSION• How is it going?• Where are you hosting?• What problems are you hitting?

• Format for presentations• 5 minutes on the demo, could go to 10 if you need to

HOMEWORK 9• Take the clearDB implementation shown in class and use JSON parsing to

render it as the cars example previously showed, except using the cloud database rather than local WebSQL