CSE 115. Introduction to Computer Science I

Similar documents
CSE 115. Introduction to Computer Science I

CSE 115. Introduction to Computer Science I

CSE 115. Introduction to Computer Science I

CSE 115. Introduction to Computer Science I

CSE 115. Introduction to Computer Science I

Client Side JavaScript and AJAX

CSE 115. Introduction to Computer Science I

Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum

Assignment: Seminole Movie Connection

Contents. Demos folder: Demos\14-Ajax. 1. Overview of Ajax. 2. Using Ajax directly. 3. jquery and Ajax. 4. Consuming RESTful services


Design Document V2 ThingLink Startup

Controller/server communication

Controller/server communication

AJAX. Ajax: Asynchronous JavaScript and XML *

CSC Javascript

CSC 309 The Big Picture

20486-Developing ASP.NET MVC 4 Web Applications

Web Application Security

REST. Web-based APIs

User Interaction: jquery


Ajax. David Matuszek's presentation,

IERG 4080 Building Scalable Internet-based Services

Developing ASP.Net MVC 4 Web Application

CITS3403 Agile Web Development Semester 1, 2018

CSCE 120: Learning To Code

COURSE 20486B: DEVELOPING ASP.NET MVC 4 WEB APPLICATIONS

20486: Developing ASP.NET MVC 4 Web Applications (5 Days)

Web Programming Paper Solution (Chapter wise)

IN Development in Platform Ecosystems Lecture 3: json, ajax, APIs

AJAX: Asynchronous Event Handling Sunnie Chung

! The final is at 10:30 am, Sat 6/4, in this room. ! Open book, open notes. ! No electronic devices. ! No food. ! Assignment 7 due 10pm tomorrow

Lesson 12: JavaScript and AJAX

AJAX and JSON. Day 8

Developing ASP.NET MVC 4 Web Applications

FUSE Ajax Tutorial. 07/06 Version 1.2

Session 11. Ajax. Reading & Reference

CSE 115. Introduction to Computer Science I

Lab 1 - Introduction to Angular

Programming in HTML5 with JavaScript and CSS3

Static Webpage Development

Ajax- XMLHttpResponse. Returns a value such as ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, based on the value of

2/6/2012. Rich Internet Applications. What is Ajax? Defining AJAX. Asynchronous JavaScript and XML Term coined in 2005 by Jesse James Garrett

welcome to BOILERCAMP HOW TO WEB DEV

Developing ASP.NET MVC 5 Web Applications. Course Outline

Ajax HTML5 Cookies. Sessions 1A and 1B

CS193X: Web Programming Fundamentals

Hyper- Any time any where go to any web pages. Text- Simple Text. Markup- What will you do

COURSE 20480B: PROGRAMMING IN HTML5 WITH JAVASCRIPT AND CSS3

AngularJS Intro Homework

TIME SCHEDULE MODULE TOPICS PERIODS. HTML Document Object Model (DOM) and javascript Object Notation (JSON)

Session 18. jquery - Ajax. Reference. Tutorials. jquery Methods. Session 18 jquery and Ajax 10/31/ Robert Kelly,

EECS1012. Net-centric Introduction to Computing. Lecture "Putting It All Together" and a little bit of AJAX

Programming in HTML5 with JavaScript and CSS3

CIW 1D CIW JavaScript Specialist.

Child Items. Adding Child Items to plugin control panels. File Structure 4. Hacking childitems.html 7. Hacking childitem.html (without the s) 14

Rico AjaxEngine Tutorial

COURSE OUTLINE MOC 20480: PROGRAMMING IN HTML5 WITH JAVASCRIPT AND CSS3

Serverless Single Page Web Apps, Part Four. CSCI 5828: Foundations of Software Engineering Lecture 24 11/10/2016

Jquery Manually Set Checkbox Checked Or Not

20486: Developing ASP.NET MVC 4 Web Applications

Full Stack Web Developer Nanodegree Syllabus

ThingLink User Guide. Andy Chen Eric Ouyang Giovanni Tenorio Ashton Yon

Working with Database. Client-server sides AJAX JSON Data formats Working with JSON data Request Response Bytes Database

CS193X: Web Programming Fundamentals

Standard 1 The student will author web pages using the HyperText Markup Language (HTML)

CSCE 120: Learning To Code

CIS 3308 Logon Homework

webkitpony Documentation

Manual Html A Href Onclick Submit Form

,

Using AJAX to Easily Integrate Rich Media Elements

Jquery Ajax Json Php Mysql Data Entry Example

Some Facts Web 2.0/Ajax Security

We are assuming you have node installed!

Developing Ajax Applications using EWD and Python. Tutorial: Part 2

Django Test Utils Documentation

Welcome to CS50 section! This is Week 10 :(

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

Course 20486B: Developing ASP.NET MVC 4 Web Applications

AJAX: Introduction CISC 282 November 27, 2018

Angular 2 Programming

Developing ASP.NET MVC 4 Web Applications

Jquery.ajax Call Returns Status Code Of 200 But Fires Jquery Error

Module 5: Javascript, Cookies COM 420

Part of this connection identifies how the response can / should be provided to the client code via the use of a callback routine.

Microsoft Programming in HTML5 with JavaScript and CSS3

Lecture 8. ReactJS 1 / 24

ASP.NET MVC Training

Course 20480: Programming in HTML5 with JavaScript and CSS3

Developing ASP.NET MVC 5 Web Applications

django-ajax-form-mixin Documentation

CS 1100: Web Development: Client Side Coding / Fall 2016 Lab 2: More HTML and CSS

An Brief Introduction to a web browser's Document Object Model (DOM) Lecture 24

CS50 Quiz Review. November 13, 2017

HTML 5 and CSS 3, Illustrated Complete. Unit L: Programming Web Pages with JavaScript

This is CS50. Harvard College Fall Quiz 1 Answer Key

20486 Developing ASP.NET MVC 5 Web Applications

CNIT 129S: Securing Web Applications. Ch 10: Attacking Back-End Components

Transcription:

CSE 115 Introduction to Computer Science I

Midterm Midterm will be returned no later than Monday. We may make midterm pickup available before then. Stay tuned.

Midterm results Module 1 Module 2 Overall avg 68.4 / 80 60.3 / 80 128.7 / 160 avg % 85.5% 75.4% 80.5% median 72 / 80 66 / 80 137 / 160 median % 90.0% 82.5% 85.6%

Road map Review JSON Chat App - Part 1 AJAX Chat App - Part 2

Front End JavaScript <html> <head></head> <body> <h1>first Web Page</h1> <p>my content</p> <div id="mydiv"></div> <script src="mycode.js"></script> </body> </html> var mydiv = document.getelementbyid("mydiv"); mydiv.innerhtml = "Content added from JavaScript";

Web Server Client Sends requests to server Client Sends requests to server Client Sends requests to server Web Server Software runs continuously and waits for requests from clients Responds to requests

import bottle Python Web Server @bottle.route("/") def any_name(): return bottle.static_file("index.html", root="") @bottle.route("/mycode.js") def another_name(): return bottle.static_file("mycode.js", root="") bottle.run(host="0.0.0.0", port=8080, debug=true)

Client Sends requests to server at "/" <html> <head></head> <body> <h1>first Web Page</h1> <p>my content</p> <div id="mydiv"></div> <script src="mycode.js"></script> </body> </html> Review Server responds with index.html index.html requires mycode.js and a second request is sent import bottle @bottle.route("/") def any_name(): return bottle.static_file("index.html", root="") @bottle.route("/mycode.js") def another_name(): return bottle.static_file("mycode.js", root="") var mydiv = document.getelementbyid("mydiv"); mydiv.innerhtml = "Content added from JavaScript"; Server responds with mycode.js bottle.run(host="0.0.0.0", port=8080, debug=true) mycode.js runs in the browser and the HTML is modified

Road map Review JSON Chat App - Part 1 AJAX Chat App - Part 2

JSON JSON.stringify(jsData) JSON.parse(jsonString) import json json.dumps(python_data) json.loads(json_string) We've seen json.loads to convert from a JSON string to python type To complete the conversions we have json.dumps to convert Python types to JSON strings JSON.stringify to convert JavaScript types to a JSON string JSON.parse to convert a JSON string to JavaScript type Whenever we send data over the Internet we'll covert it to a JSON string

Road map Review JSON Chat App - Part 1 AJAX Chat App - Part 2

Chat App - Overview Goal: Build an app where users can send chat messages to all other users To build this app we will need An HTML file that will be displayed to the user (JavaScript) A function that will modify the HTML to display the chat history to the user (JavaScript) A function that will allow the user to submit a new chat message (Python) A server that will host our HTML, JavaScript, and chat messages (Python) Function to save and load the chat history in a file that will persist ever if the server restarts A way for the JavaScript front-end to communicate with the Python back-end

Chat App - Overview Note: There are many possible ways to build this app We'll walk through only one possible design, though there are many other solutions

Chat App - File Structure We'll create the following files for our chat app index.html chat.js server.py chat.txt chat.py

Chat App - index.html <html> <head> <script src="chat.js"></script> </head> <body onload="loadchat();"> Message: <input type="text" id="message"> <button onclick="sendmessage();">send</button> <hr/> <div id="chat"></div><br/> </body> </html>

Chat App - index.html <html> <head> <script src="chat.js"></script> </head> <body onload="loadchat();"> Message: <input type="text" id="message"> <button onclick="sendmessage();">send</button> <hr/> <div id="chat"></div><br/> </body> </html> Download the JavaScript portion of the app

Chat App - index.html <html> <head> <script src="chat.js"></script> </head> <body onload="loadchat();"> Message: <input type="text" id="message"> <button onclick="sendmessage();">send</button> <hr/> <div id="chat"></div><br/> </body> </html> Instead of adding the script tag at the bottom of the body so it runs after the page loads we'll download it earlier and run it using the onload property to call a JavaScript function

Chat App - index.html <html> <head> <script src="chat.js"></script> </head> <body onload="loadchat();"> Message: <input type="text" id="message"> <button onclick="sendmessage();">send</button> <hr/> <div id="chat"></div><br/> </body> </html> Add an empty div where our JavaScript can write the chat history

Chat App - index.html <html> <head> <script src="chat.js"></script> </head> <body onload="loadchat();"> Message: <input type="text" id="message"> <button onclick="sendmessage();">send</button> <hr/> <div id="chat"></div><br/> </body> </html> Add 2 new HTML elements An input with a type of text gives the user a text box A button that calls one of our JavaScript functions whenever the user clicks it

function loadchat(){... } Chat App - chat.js function sendmessage(){... } We'll define these later, but chat.js will need these two functions loadchat() Gets the chat history from the server and displays in the chat div sendmessage() Reads the value in the text box and sends it the server as a new chat message Updates the chat history

Chat App - chat.txt This file will store all of the chat history We won't add anything to this file manually, but we'll manually create it as an empty file This file will store one chat message per line

Chat App - chat.py filename = "chat.txt" def get_chat(): full_chat = [] with open(filename) as file: for line in file: full_chat.append({"message": line.rstrip("\n\r")}) return full_chat def add_message(message): with open(filename, "a") as file: file.write(message + "\n")

Chat App - chat.py filename = "chat.txt" define a filename variable outside of any function (at the module level) This variable can be used by any functions in this file This allows us to switch files by making only one change in our code

Chat App - chat.py def add_message(message): with open(filename, "a") as file: file.write(message + "\n") We'll call this function each time we get a new message from a user Open chat.txt in append mode and write the message followed by a new line

Chat App - chat.py def get_chat(): full_chat = [] with open(filename) as file: for line in file: full_chat.append({"message": line.rstrip("\n\r")}) return full_chat Read all the chat messages from a file and add them to a list as a dictionary with a key "message" Our JavaScript code will expect this same format

Chat App - Server import bottle import json import chat @bottle.route('/') def index(): return bottle.static_file("index.html", root="") @bottle.route('/chat.js') def static(): return bottle.static_file("chat.js", root="") @bottle.route('/chat') def get_chat(): return json.dumps(chat.get_chat()) @bottle.post('/send') def do_chat(): content = bottle.request.body.read().decode() content = json.loads(content) chat.add_message(content['message']) return json.dumps(chat.get_chat()) bottle.run(host="0.0.0.0", port=8080, debug=true)

Chat App - Server import bottle import json import chat We'll need bottle and json so we import those package Since we have python code across 2 files we also need to import our chat file Since there files are in the same directory we can import using it's name, without the ".py" We can now call chat.add_message(message) and chat.get_chat() just like we call function from built-in modules

Chat App - Server... @bottle.route('/') def index(): return bottle.static_file("index.html", root="") @bottle.route('/chat.js') def static(): return bottle.static_file("chat.js", root="")... Host our 2 front end files The user will access our root path "/" to get index.html In our HTML we have a script tag referencing chat.js which will trigger a second HTTP requests with a path of "/chat.js"

Chat App - Server... @bottle.route('/chat') def get_chat(): return json.dumps(chat.get_chat()) @bottle.post('/send') def do_chat(): content = bottle.request.body.read().decode() content = json.loads(content) chat.add_message(content['message']) return json.dumps(chat.get_chat())... Set up paths that will be accessed from our JavaScript code We need to convert to/from JSON strings whenever data is being sent/ received from the front-end

Chat App - Server... @bottle.post('/send') def do_chat(): content = bottle.request.body.read().decode() content = json.loads(content) chat.add_message(content['message']) return json.dumps(chat.get_chat())... We label this as a post path to limit this to HTTP POST requests POST is a way to say that this path expects the user to send information to the server This information will be stored in the body of the request

Chat App - Server... @bottle.post('/send') def do_chat(): content = bottle.request.body.read().decode() content = json.loads(content) chat.add_message(content['message']) return json.dumps(chat.get_chat())... To read the data in the HTTP request containing a new chat message we will read the variable "bottle.request.body" which contains the body of the request in a similar format as the response of an HTTP request when we connected to APIs This path expects the body of the request to be a JSON string in the format {"message": <message_content>} It is important that both our Python and JavaScript code use the same format

Chat App - Server... bottle.run(host="0.0.0.0", port=8080, debug=true) And finally, start the server

Chat App - Check Point Now we have our server setup that will Serve our HTML and JavaScript files Accept new chat message and save them to a file at the path "/send" Return the entire chat history at the path "/chat" The chat history will persist even if the server restarts What we need next is to write our JavaScript functions that will make requests to the paths

Chat App - Check Point However, the only way we have to make HTTP requests from the front end is to Type a URL in our browser Add script tags in the HTML that download JavaScript files How do we make requests to "/send" and "/chat" after the page loads? How do we make a POST requests with a body containing a chat message?

Road map Review JSON Chat App - Part 1 AJAX Chat App - Part 2

AJAX Asynchronous JavaScript Because everything related to web development needs its own acronym.. A way to make HTTP request from JavaScript after the page is fully loaded Can make HTTP GET requests (Request content from a server) Can make HTTP POST requests (Send content to a server)

AJAX - HTTP GET Request function ajaxgetrequest(path, callback){ var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if (this.readystate === 4 && this.status === 200){ callback(this.response); } }; request.open("get", path); request.send(); } There are many different ways to setup an AJAX call We setup the call in a function that takes The path where we want to send the requests (matches the paths in the annotations of the bottle server) A callback function. This function will be called when the server responds to our requests with the response as an argument

AJAX - HTTP GET Request function ajaxgetrequest(path, callback){ var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if (this.readystate === 4 && this.status === 200){ callback(this.response); } }; request.open("get", path); request.send(); } To avoid being distracted by the details, you may paste this function in your JavaScript where it's needed and call this function whenever you need to make an AJAX request

AJAX - HTTP POST Request function ajaxpostrequest(path, data, callback){ var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if (this.readystate === 4 && this.status === 200){ callback(this.response); } }; request.open("post", path); request.send(data); } To make a POST request most of the code is the same The major difference is that we have a third parameter named data which must be a string containing the data that will be in the body of the request

AJAX - HTTP POST Request function ajaxpostrequest(path, data, callback){ var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if (this.readystate === 4 && this.status === 200){ callback(this.response); } }; request.open("post", path); request.send(data); } As with the AJAX GET request you may paste this function where needed so we don't get distracted by this syntax and these details

AJAX - Calling the Functions function action_on_response(response){ console.log("the server responded with: " + response); } function called_on_button_press(){ ajaxpostrequest("/some_path", "Button pressed", action_on_response); } To make an AJAX POST request we need to call the ajaxpostrequest function with a path, data, and a callback function When the function called_on_button_press is called it will send an AJAX POST request 1. To the path "/some_path" which must match a path of the same name in the bottle server 2. With a body of "Button pressed" (We will send JSON strings in our apps) 3. When the server responds to this request our action_on_response function will be called with the response from the server

AJAX - Calling the Functions function action_on_response(response){ console.log("the server responded with: " + response); } function called_on_button_press(){ ajaxpostrequest("/some_path", "Button pressed", action_on_response); } Note that we do not use parentheses when passing the action_on_response function as an argument We are passing the entire function as an argument. Not the evaluation of a call of this function The function will be called latter by the AJAX function [Calling ajaxgetrequest works the same way except we don't pass a data argument]

Road map Review JSON Chat App - Part 1 AJAX Chat App - Part 2

Chat App Continued Now that we have a way to communicate with our server after the page is loaded we can finish our chat app To do this we will make an AJAX get request after the page loads to get and display the current chat history Then we will make an AJAX POST request each time the user clicks the button to send a message

Chat App - chat.js function renderchat(response){ var chat = ""; for(var data of JSON.parse(response).reverse()){ chat = chat + data.message + "</br>"; } document.getelementbyid("chat").innerhtml = chat; } function loadchat(){ ajaxgetrequest("/chat", renderchat); }... Recall loadchat is called after the HTML is finished loading The response from the server at "/chat" is a JSON string representing a list of objects where each object contains a key "message"

Chat App - chat.js function renderchat(response){ var chat = ""; for(var data of JSON.parse(response).reverse()){ chat = chat + data.message + "</br>"; } document.getelementbyid("chat").innerhtml = chat; } function loadchat(){ ajaxgetrequest("/chat", renderchat); }... loadchat initiates the AJAX GET request at the path "/chat" to get the current chat history from the server The callback function is renderchat which parses the JSON string and iterates over the array while accumulating a string storing HTML The callback then sets this HTML to the div with the id "chat"

Chat App - chat.js function sendmessage(){ var messageelement = document.getelementbyid("message"); var message = messageelement.value; messageelement.value = ""; var tosend = JSON.stringify({"message": message}); } ajaxpostrequest("/send", tosend, renderchat); Recall Send message is called when the user clicks the send button There is a text box with the id "message" on the page The "/send" path on our server expects a JSON string representing an object with a key of "message"

Chat App - chat.js function sendmessage(){ var messageelement = document.getelementbyid("message"); } var message = messageelement.value; messageelement.value = ""; var tosend = JSON.stringify({"message": message}); ajaxpostrequest("/send", tosend, renderchat); When the sendmessage function is called (the button is clicked) it will initiate an AJAX POST request to the "/send" path The data to be sent is pulled from the text box input by accessing its "value" property. This property contains the text that the user has entered The server responds with the updated chat history so our callback the same renderchat function as we used for the GET request

Chat App We now have a fully functional chat app that uses JavaScript and AJAX calls to communicate with a python web server that saves the chat history in a persistent file

Chat App - Expansions Our app works just fine, but it could benefit from improvements. Here are few ideas that could expand this app Make it pretty The app has no style. We could use CSS, Bootstrap, etc to improve the aesthetics of the app Live updates Users only see new messages when they either send a message or refresh the page We could improve this by using polling, long-polling, or web sockets Keyboard shortcuts Allow users to send a message by hitting the enter key

Chat App - Polling... <body onload="setinterval(loadchat, 2000);">... Instead of loading the content once, call setinterval Calls loadchat every 2000 ms (2 seconds) User will see live chat with at most a 2 seconds delay Not the best way to get updates from the server, but it is the simplest Creates a lot of traffic tradeoff between delays and server traffic ex: 100 users @ 2 second polling = 50 requests per second

Chat App - Enter to Send... Message: <input type="text" id="message" onkeypress="checkenter(event);">... function checkenter(keyupevent){ if(keyupevent.keycode === 13){ sendmessage(); } } Use the onkeypress attribute to call a new JavaScript function whenever a key is pressed Use checkenter to check if the enter key is pressed Every key has a key code the key code for enter is 13

Chat App - Expansions Now that we have the foundation of app we can build upon with significantly less effort than it took to create the app What can you build?