Download presentation
Presentation is loading. Please wait.
Published byNoah Mills Modified over 9 years ago
1
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Written by Matthew Shelley for Professor Wei Shi Break = 15 minutes Buffer = 15 minutes Total Time = 150 minutes (2h30m)
2
Data Storage [Time = 5 minutes for this section]
3
Data Storage It is often necessary to store game information, which may or may not change In a single-player game, one file is often sufficient For instance, we might read settings from an XML file For an online social game, however, each user may have their own information, which could be shared A database such as MySQL can fulfill this need Please note that XML files cannot be modified locally due to security issues; however, web hosts will allow it. For instance, PHP could be used to modify an XML file on the server-side.
4
XML and AJAX [Time = 10 minutes for slides + 35 minutes for demo = 45 minutes for this section]
5
XML XML serves the purposes of describing data
Typically in a hierarchical fashion While XML and HTML are structurally very similar, XML does not do anything with the data it describes A basic tag / element: <tagname attr1=“value1” ... /> A more complicated tag / element: <tagname attr1=“value1” ...>...</tagname> Tags in XML are ‘custom’ in that the developer defines them. XML is very strict with its formatting, unlike HTML. HTML pages can be written in pure XML; these pages are referred to as XHTML I often use tag and element interchangeably. For argument’s sake though, a tag is the ‘written code’ while an element is what its ‘representation’. Additional tags can exist between the opening and closing tags, just like in HTML
6
XML All XML files should begin with
<?xml version="1.0" encoding="ISO "?> Comments are written just like in HTML <!-- COMMENT --> Complex data using < and & should be wrapped with <![CDATA[ and ]]>, e.g. <![CDATA[<notatag>&&&&</notatag>]]> The encoding attribute can be removed. CDATA can only exist in the ‘content’ section of a tag, not the attributes – at least to my knowledge I have noticed that the .text() method in jQuery does not return the content within CDATA
7
XML Example – Multiple Choice Quiz
<?xml version="1.0" encoding="ISO "?> <quiz> <question q=“Is true false?” correctvalue=“2”> <answer value=“1”>True</answer> <answer value=“2”>False</answer> </question> <question …> … ... </quiz> Be sure to include the very first line in all XML documents. There are variants to this line, but this one works fine.
8
Parsing XML with jQuery
With an XML file written, we need to be able to read the data within and then use it To do so, we first load the file with AJAX and then parse it with jQuery similar to HTML $.ajax(…) $(xml).find(‘tag’) $(xml).children(‘tag’) $(xml).attr(‘attribute’) $(xml).text() $.ajax(…) -Used to load the XML file $(xml).find(‘tag’) -xml is some element, which can be returned in the $.ajax() call -Finds all instances of tag within the current xml element -Does not account for depth $(xml).children(‘tag’) -Finds a tag that is a child of the element in xml $(xml).attr(‘attribute’) -Retrieves an attribute’s value $(xml).text() -Returns the text between the opening and closing tag -This function may produce undesirable outcome if there are more tags in between
9
AJAX “Asynchronous JavaScript and XML” is used to communicate between the client and the server in the background, similar to WebSockets Data is sent through either GET or POST methods GET: data is visible in the URL POST: data is not visible in the URL Refer to “type” in the upcoming example Essentially, AJAX requests a URL, possibly with data sent along, and returns the server’s response Despite the name… -XML does not have to be used, as any textual form of data can be returned (to my knowledge) -Communication can also be performed synchronously, if so desired Explain GET and POST in greater detail, if you wish AJAX is desirable for those who only have access to have a basic web server with some sort of server-side language (e.g. PHP)
10
AJAX + XML Example The example provided reads in an XML file containing three users, and then displays the results to a table on the web page Please refer to ajax_example.htm ajax_example.xml js/ajax_example.js [Time = 35 minutes for demonstration] Start by creating a basic HTML5 page from the template. Then, create an XML file with some generic user data, following the format given. Afterward, write out or open the JavaScript file. Describe the JavaScript file or code along in this form… Namespace Calling init() via $(document).ready(…) The init() method within the example, which loads the XML file via AJAX Notice how the XML parsing is similar to the structure of the XML data itself The User class is just a means of hiding away details Sometimes XML files cannot be read locally due to security issues. I find this problem occurs in Google Chrome.
11
Useful Links XML Introduction CDATA AJAX via jQuery
CDATA AJAX via jQuery
12
XAMPP [Time = 20 minutes due to installation]
I recommend using the time to review content previously taught, and allowing students to ask questions. Alternatively, if you have XAMPP already installed, please feel free to move on with the lecture. I am assuming that 20 minutes will be focused on the installation and some review, as far as my timing is concerned.
13
XAMPP XAMPP allows you to treat your computer like a web server, which is helpful for when you want to develop outside of a live website Installing XAMPP gains access to: Apache MySQL PHP phpMyAdmin And a few others... Be sure to turn on Apache when you use phpmyAdmin
14
Download and Install XAMPP
To download XAMPP, select your version from: Launch the installer file It may be necessary to install XAMPP through “Run as Administrator” on Windows Unless you know what to exclude, get everything Installation will take 15 – 20 minutes Installation is expected to take 15 – 20 minutes -Or, it did on my netbook at least Start the download and installation process prior to the break. If necessary, it is okay to let this process continue on throughout the break. Just make sure everyone is ready to proceed after the break. -- Please keep in mind: Students may be unable to takes notes on their computers during the installation process. ^ If students have problems after turning on Apache, let them know that Skype might be conflicting. ^ This video just explains the installation process, and does not need to be shown
15
MySQL Databases [Time = 5 minutes for this section; 75 minutes total come the break]
16
What is a database? A database is a collection of tables, where a table is a collection of entries (rows) with associated data (columns) We perform queries on these tables Select Insert Update Delete There are other types of queries, such as for manipulating tables
17
Example Tables: ‘users’ + ‘friends’
user_id username password 1 User_1 Pass_1 2 User_2 Pass_2 3 User_3 Pass_3 In this example, all players are friends with all other players user_id friend_id 1 2 3
18
What Are Queries? Queries describe ‘what we want to find’ or ‘what we want to happen’ rather than ‘how we will find it’ or ‘how we will make it happen’ For example, “SELECT userid FROM users” selects all user ids from the user tables But, we are not specifying how this operation occurs! In fact, queries even tend to optimize themselves These queries are performed on the server-side using languages such as PHP or extensions like node-mysql (as will be our case) Queries are a calculus – elaborate? Could also elaborate on queries optimizing themselves -You can mention keys for this purpose as well For clarity, it is helpful to write all keywords in capital letters.
19
Break – 15 minutes [Time = 75 minutes before the break; 75 minutes after the break]
20
MySQL Queries [Time = 15m for this section; 60m will remain after this section] The SELECT examples use the table shown earlier
21
MySQL SELECT – Example 1 SELECT * FROM users
Returns all rows from ‘users’ with all columns user_id username password 1 User_1 Pass_1 2 User_2 Pass_2 3 User_3 Pass_3
22
MySQL SELECT – Example 2 SELECT username FROM users
Returns all usernames username User_1 User_2 User_3
23
MySQL SELECT – Example 3 SELECT userid, username FROM users ORDER BY userid DESC LIMIT 1 Retrieves the newest user’s userid and username user_id username 3 User_3 ASC = Ascending (increasing) DESC = Descending (decreasing)
24
MySQL SELECT – Example 4 SELECT * FROM users WHERE ( = AND password = ‘password1’) LIMIT 1 Such a query would be useful for verifying that the user has provided the correct login information Of course, the password should be encrypted Since user input is often inserted into queries, it is important to sanitize this input to avoid harmful “SQL injection” Values must be escaped, e.g. ‘St. John\’s’ Double quotes are usually acceptable as well. The MySQL demos do include sanitization to avoid harmful SQL injection
25
MySQL INSERT - Examples
INSERT INTO users (username, password, ) VALUES (‘User 1’, ‘password1’, INSERT INTO users SET username = ‘User 1’, password = ‘password1’, = It is important to note that if any keys are duplicated, the result may be rejected. As we are not discussing keys, it is sufficient to inform students to check if the entry already exists. We can add an auto_increment to the ‘userid’ in order for that value to automatically be set. This feature will be covered in table creation for phpMyAdmin. It is also possible to INSERT rows from a SELECT query
26
MySQL UPDATE - Example UPDATE users SET username = ‘some_user’, password = ‘some_password’ WHERE userid = 2 LIMIT 1 The WHERE clause is very important, otherwise all rows will be updated
27
MySQL DELETE - Examples
DELETE FROM users WHERE userid = ‘1’ LIMIT 1 DELETE FROM some_table ORDER BY datetime_of_access DESC LIMIT 1 We only want to delete 1 row. If there is only 1 such row, we need not specify the LIMIT. LIMIT is useful for DELETE queries that feature ‘ORDER BY’. For instance, we can remove the oldest row in the second example.
28
Useful Links Select Insert Update Delete
Insert Update ml Delete
29
phpMyAdmin [Time = 10 minutes for this section; 50 minutes will remain afterward] I suggest a live demo of phpMyAdmin, but otherwise you can refer to the screenshots provided
30
phpMyAdmin phpMyAdmin manages MySQL databases and users, which are assigned privileges To access phpMyAdmin: Start Apache via XAMPP Start MySQL Click ‘Admin’ for MySQL to open phpMyAdmin
31
Create Database With phpMyAdmin open, click the “Databases” tag atop the page Name your database and then press “Create” I created a database called “mysql_demo,” which is used in all my mysql examples
32
Create a User From the database section, go to “Privileges”
You can see users assigned to this database You can modify privileges of such users You can also create a new user For test purposes, I made User “user_demo” with Password “dummy” Grant all privileges on database “mysql_demo” Should not need to worry about other settings In my examples, I ended up using another user instead of the one I created…
33
Create a User
34
Create a Table Click the “Create Table” button on the left menu
Enter the table name and number of columns A few notes… “varchar 255” is a string of length 255 The primary key uniquely identifies a row auto_increment (A_I) can be given to only one column, providing it is a key Feel free to discuss keys in greater detail, but I think that matter is best saved for a course on databases
35
Create a Table Notice “A_I” (auto_increment) tag is specified for the user id. Doing so allows this value to increment for every inserted row.
36
Modify a Table To modify a table go to its ‘structure’ tab
Each column can be modified or removed entirely You can also add new columns
37
Additional Table Operations
From the “database” structure, you can… Browse – view rows in a table Structure – view table structure Search – perform a query on a table Insert – add rows to a table Empty – delete all rows in a table Drop – delete the entire table
38
MySQL Demos [Time = 50 minutes for TWO demos]
Remember to turn on MySQL through XAMPP You will also want to turn off Apache when using the socket.io demo
39
Using node-mysql To install node-mysql via command prompt:
npm install Load the module in code with var mysql = require(‘mysql’); Refer to server-mysql.js and run it via node.js [Time = 25 minutes] Describe this example in the linear form given (see js/server-mysql.js). If desired, feel free to code along with the students as well.
40
Using Socket.io + MySQL Socket.io is an event-driven API that greatly simplifies sending and receiving messages socket.on(“eventname”, function(data) {…}) Add event listener to any arbitrary event in order to receive data, e.g. an associative array socket.emit(“eventname”, data) Send along data for an arbitrary event [Time = 25 minutes] Remember to turn off Apache when running socket.io as we want to connect to port 80 Run the server code (js/server-mysql-socketio.js) through node as per usual. Open the client-mysql-socketio.htm demo in a web browser. The comments should be enough to explain the code. I am simply setting up a few callbacks via .on() to receive data AND sending data through .emit() This demo continues to use node-mysql from before! Nothing changes with how MySQL is handled. It is probably unnecessary to code this demo along with students.
41
Useful Links mysql-node Socket.io
Socket.io Advanced HTML5 JavaScript: Down 'n Dirty
42
One last thing… Feel free to drop these slides, if you wish. I just thought it might be worthwhile to mention PHP :)
43
PHP There are many server-side languages, though PHP is a common one
If you are using AJAX, you will most likely end up using PHP for your server-side scripts, as it is available with most web hosts PHP is outside of the scope of this lecture, but here are a few examples...
44
Common MySQL Functions in PHP
These PHP functions are used with MySQL: mysql_connect() mysql_select_db() mysql_query() mysql_fetch_assoc() mysql_error()
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.