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

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

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

So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

Assignment: Seminole Movie Connection

AJAX. Ajax: Asynchronous JavaScript and XML *

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

,

User Interaction: jquery

IN Development in Platform Ecosystems Lecture 2: HTML, CSS, JavaScript

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 07 Minor Subject

Welcome to CS50 section! This is Week 10 :(

CSCE 120: Learning To Code

CSCE 120: Learning To Code

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 06 (Haup-ach)

This project will use an API from to retrieve a list of movie posters to display on screen.

HTTP Communication on Tizen


JavaScript Specialist v2.0 Exam 1D0-735

AJAX: Introduction CISC 282 November 27, 2018

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

AJAX. Lab. de Bases de Dados e Aplicações Web MIEIC, FEUP 2010/11. Sérgio Nunes

CSC Web Technologies, Spring Web Data Exchange Formats

Jquery Ajax Json Php Mysql Data Entry Example

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

16. Objects & JSON. Dr. Dave Parker. Informa;on and the Web, 2014/15

Human-Computer Interaction Design

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

APEX Unplugged Building Oracle Application Express Applications That Can Survive Without the Internet. Dan McGhan Senior Technical Consultant

XMLHttpRequest. CS144: Web Applications

CSC 309 The Big Picture

AJAX. Lecture 26. Robb T. Koether. Fri, Mar 21, Hampden-Sydney College. Robb T. Koether (Hampden-Sydney College) AJAX Fri, Mar 21, / 16

Working with Javascript Building Responsive Library apps

JavaScript Fundamentals_

CSE 115. Introduction to Computer Science I

Using AJAX to Easily Integrate Rich Media Elements

Lesson 12: JavaScript and AJAX

Making a Clickable Map Display

SEEM4570 System Design and Implementation. Lecture 4 AJAX and Demo

Project Part 2 (of 2) - Movie Poster And Actor! - Lookup

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

Intro To Javascript. Intro to Web Development

CS312: Programming Languages. Lecture 21: JavaScript

CSCI 201L Written Exam #1 Fall % of course grade

CS50 Quiz Review. November 13, 2017

Why Discuss JavaScript? CS312: Programming Languages. Lecture 21: JavaScript. JavaScript Target. What s a Scripting Language?

Client Side JavaScript and AJAX

XML Processing & Web Services. Husni Husni.trunojoyo.ac.id

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

Session 11. Ajax. Reading & Reference

Varargs Training & Software Development Centre Private Limited, Module: HTML5, CSS3 & JavaScript

AngularJS AN INTRODUCTION. Introduction to the AngularJS framework

CSE 115. Introduction to Computer Science I

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

Course 20480: Programming in HTML5 with JavaScript and CSS3

COURSE 20480B: PROGRAMMING IN HTML5 WITH JAVASCRIPT AND CSS3

Licence CRRW IUT de Marne-la-Vallée 26/01/2018. AJAX with jquery. Philippe Gambette

Dingle Coderdojo 6. Project Part 2 (of 2) - Movie Poster And Actor! - Lookup. Week 6

In this exercise we shall be using jsfiddle.net to build a simple data driven web site in HTML5. Building Blocks

Microservices with Node.js

AJAX: The Basics CISC 282 March 25, 2014

Homework 8: Ajax, JSON and Responsive Design Travel and Entertainment Search (Bootstrap/Angular/AJAX/JSON/jQuery /Cloud Exercise)

Programming in HTML5 with JavaScript and CSS3

CS193X: Web Programming Fundamentals

DECOUPLING PATTERNS, SERVICES AND CREATING AN ENTERPRISE LEVEL EDITORIAL EXPERIENCE

CS 498RK FALL RESTFUL APIs

The course also includes an overview of some of the most popular frameworks that you will most likely encounter in your real work environments.

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

Web Development 20480: Programming in HTML5 with JavaScript and CSS3. Upcoming Dates. Course Description. Course Outline

Networking & The Web. HCID 520 User Interface Software & Technology

SEEM4570 System Design and Implementation. Lecture 6 Game Part II

Networking & The Web. HCID 520 User Interface Software & Technology

WebApp development. Outline. Web app structure. HTML basics. 1. Fundamentals of a web app / website. Tiberiu Vilcu

Session 11. Calling Servlets from Ajax. Lecture Objectives. Understand servlet response formats

Elementary! Incorporating BlueMix, Node-RED and Watson in Domino applications

HTTP Communication on Tizen (Tizen Ver. 2.3)

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains an Individual and Group component

AJAX: The Basics CISC 282 November 22, 2017

FUSE Ajax Tutorial. 07/06 Version 1.2

Course Details. Skills Gained. Who Can Benefit. Prerequisites. View Online URL:


Web Application Security

Events & Callbacks (ESaaS 6.5)! 2013 Armando Fox & David Patterson, all rights reserved

Create-A-Page Design Documentation

jquery with Fundamentals of JavaScript Training

Programming for Digital Media. Lecture 7 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Kyle Rainville Littleton Coin Company

Programming in HTML5 with JavaScript and CSS3

Asynchronous JavaScript + XML (Ajax)

Ajax HTML5 Cookies. Sessions 1A and 1B

! 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

AJAX. Introduction. AJAX: Asynchronous JavaScript and XML

AJAX: From the Client-side with JavaScript, Back to the Server

Controller/server communication

What is Node.js? Tim Davis Director, The Turtle Partnership Ltd

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

THE PRAGMATIC INTRO TO REACT. Clayton Anderson thebhwgroup.com WEB AND MOBILE APP DEVELOPMENT AUSTIN, TX

ASP.NET AJAX adds Asynchronous JavaScript and XML. ASP.NET AJAX was up until the fall of 2006 was known by the code-known of Atlas.

AJAX Workshop. Karen A. Coombs University of Houston Libraries Jason A. Clark Montana State University Libraries

BEFORE CLASS. If you haven t already installed the Firebug extension for Firefox, download it now from

A synchronous J avascript A nd X ml

Transcription:

IN5320 - Development in Platform Ecosystems Lecture 3: json, ajax, APIs 3rd of September 2018 Department of Informatics, University of Oslo Magnus Li - magl@ifi.uio.no 1

Today s lecture 1. Objects and Json 2. Ajax and APIs 3. Deferred and Promise 2

First presentation moved to week 42! 3

Objects and JSON 4

JavaScript objects JavaScript allows us to create objects. Objects in JavaScript is just a collection of key - value pairs /named values var room = { name:"ada", number:3407, floor:3, type:"datastue" }; //Access variable room.name; //Change variable room.name = "Lisp"; 5

JavaScript objects We can at any time add new variables to our object. var room = { name:"ada", number:3407, floor:3, type:"datastue" }; //Add new variable room.size = 35; 6

JavaScript object methods Objects can also contain functions var room = { name:"ada", number:3407, floor:3, type:"datastue", getdescription: function() { return this.name + " is a " + this.type + " located on floor " + this.floor; }, }; 7

JavaScript Object Notation (JSON) JSON is a syntax for storing and exchanging data. In text-format using the JavaScript object notation standard. Name of variable as string { "name":"ada", "number":3407, "floor":3, "type":"datastue" } Value of variable 8

JSON nested objects JSON objects can contain arrays and new objects In the example below, we have an object rooms with an array of three objects representing different rooms. {"rooms":[ { "name":"john", "number":"3407", "type":"datastue" }, { "name":"awk", "number":"3118", "type":"møterom" }, { "name":"assembler", "number":"3417", "type":"terminalstue" } ]} 9

JSON + JavaScript JSON is convenient since the format is immediately compatible with JavaScript. In the example below, we store the JSON in a variable. We can access the variables of the objects as a normal JavaScript object. var ifi = {"rooms":[ { "name":"john", "number":"3407", "type":"datastue" }, { "name":"awk", "number":"3118", "type":"møterom" }, { "name":"assembler", "number":"3417", "type":"terminalstue" } ]}; console.log(ifi.rooms[0].name); 10

JSON parse and stringify Often, JSON is stored as a string in a local text file, or transfered in pure text from the server. We can then use JSON.parse() to convert it to a JavaScript Object Similarly, we can convert a JavaScript object to a JSON string with the JSON.stringify() method. var dataasstring = '{ "name":"ada", "number":3407, "floor":3, "type":"datastue" }'; var dataasjsobject = JSON.parse(dataAsString); var stringagain = JSON.stringify(dataAsJSObject); 11

JSON parse and stringify Our app in the browser Request some data Some web-server JSON.parse() JSON in string format 12

WHAT TO SEND, AND HOW? 13

Development in Platform Ecosystems This course focus on developing applications within platform ecosystems. We communicate with other resources within these platforms using APIs These APIs can provide us with data, or we can send data to them to interact with the platforms core resources, or other components. API Platforms / external resources Our app API API 14

Development in Platform Ecosystems This exchange of information is often reliant on JSON. API Platforms / external resources Our app Request JSON API Exchange JSON Exchange JSON API 15

APIs Our app 16

AJAX 17

AJAX AJAX = Asynchronous JavaScript And XML Asynchronous in that requests can run in parallel with the main thread. Transfer of data can happen without affecting other dynamic components of the web-application. Allows transfer of data in formats such as XML, JSON or plain text. In essence, ajax allows you to: Read data from a web-server after the web-page has loaded. Update a web page without reloading the page. Send data to a server in the background (without reloading the page). 18

AJAX AJAX uses the browser built-in XMLHttpRequest object to request data from a server. By sending a request to a server, this is processed and data is returned. Our app in the browser Some web-server 1. - Some event, for example button click - Send HttpRequest 2. - Process HttpRequest. - Create response, which is sent back to client. 3. - Process returned data with JavaScript - Update page content 19

AJAX jquery has some neat functionality to make AJAX-calls easy $.ajax({ datatype: "json", url: url, success: success }); Type of data, for example json Url to the location of the data What to do when data is successfully retrieved. e.g https://api.chuck norris.io/ 20

AJAX In this example, we use the API of chucknorris.io to get a random joke. Our call returns a json object containing several elements. $.ajax({ datatype: "json", url: "https://api.chucknorris.io/jokes/random", success: function(data) { }, }); console.log(data); 21

AJAX data.value gives us the random chuck norris quote $.ajax({ datatype: "json", url: "https://api.chucknorris.io/jokes/random", success: function(data) { console.log(data.value); }, }); 22

AJAX We can easily present this data in the HTML-document. <body> <p id="norris_joke"></p> </body> $.ajax({ datatype: "json", url: "https://api.chucknorris.io/jokes/random", success: function(data) { $("#norris_joke").text(data.value); }, }); 23

AJAX <p id="norris_joke"></p> <button id="get_joke">get new joke</button> $("#get_joke").click(function() { $.ajax({ datatype: "json", url: "https://api.chucknorris.io/jokes/random", success: function(data) { console.log(data.value); $("#norris_joke").text(data.value); }, }); }); 24

AJAX 25

AJAX + jquery jquery provide an even shorter syntax for retrieving json. Long $.ajax({ datatype: "json", url: "https://api.chucknorris.io/jokes/random", success: function(data) { $("#norris_joke").text(data.value); }, }); $.getjson("https://api.chucknorris.io/jokes/random", function(data) { Short }); $("#norris_joke").text(data.value); 26

AJAX + jquery jquery provide an even shorter syntax for retrieving json. URL to data Success-function $.getjson("https://api.chucknorris.io/jokes/random", function(data) { }); $("#norris_joke").text(data.value); 27

APIs 28

Interacting with the API Most APIs can be interacted with to provide us specific data We can do this by providing variables through the URL. In the example below, we use the OMDb API to search for a movie. We thus need to provide the title of the movie in the URL OMDb require a authorization key, so this is also provided in the URL http://www.omdbapi.com/?t=there+will+be+blood&apikey=574a2d9f Search string Auth key 29

What do you want to do in the seminar groups? https://goo.gl/ilz6bk 30

Example: movie rating search Say we write the following HTML code, to enable users to enter the title of a movie, click a button, and the title and IMDB rating will appear in two paragraphs. <body> <input id="keyword" type="text" placeholder="enter movie title"></input> <button id="find_button">find Ratings</button> <p id="movie_title"></p> <p id="imdb_rating"></p> </body> 31

Example: movie rating search We first need to add an event-listener on the button. Then retrieve the keyword entered by the user in the input-field. $("#find_button").click(function() { }); var keyword = $("#keyword").val(); //get search-string from input element 32

Example: movie rating search We then write the code to retrieve from the API using ajax. The keyword retrieved from the input-field is added to the URL-string in the ajax call. To test, we log the retrieved data to the console. $("#find_button").click(function() { var keyword = $("#keyword").val(); //get search-string from input element $.getjson("http://www.omdbapi.com/?t=" + keyword + "&apikey=574a2d9f", function(data) { console.log(data); }); }); Keyword provided by the user 33

Example: movie rating search Having located the Title in the json data object, we print it to the HTML document. $("#find_button").click(function() { var keyword = $("#keyword").val(); //get search-string from input element }); $.getjson("http://www.omdbapi.com/?t=" + keyword + "&apikey=574a2d9f", function(data) { }); $("#movie_title").text(data.title); 34

Example: movie rating search We then print the IMDB-rating which is located in the array Ratings in the json object. $("#find_button").click(function() { var keyword = $("#keyword").val(); //get search-string from input element }); $.getjson("http://www.omdbapi.com/?t=" + keyword + "&apikey=574a2d9f", function(data) { console.log(data); $("#movie_title").text(data.title); $("#imdb_rating").text(data.ratings[0].value); }); 35

Example: movie rating search 36

Deferred and Promise 37

Asynchronous calls Calls to APIs and happens asynchronously. That is, another thread is created in parallel to the main thread to handle the call. This can create challenges when we want to synchronize our events. Main thread AJAX call 38

Asynchronous calls Let s say we want to display a waiting screen while our application is requesting and retrieving data from a server. showwaitingscreen() hidewaitingscreen() Main thread AJAX call 39

Asynchronous calls Main thread AJAX call showwaitingscreen(); $.getjson("https://api.chucknorris.io/jokes/random", function(data) { $("#norris_joke").text(data.value); }); hidewaitingscreen(); 40

Asynchronous calls Main thread AJAX call showwaitingscreen(); $.getjson("https://api.chucknorris.io/jokes/random", function(data) { $("#norris_joke").text(data.value); hidewaitingscreen(); }); 41

Asynchronous calls With several API-calls these nested actions can become confusing. Often referred to as callback hell For example, what if we want to use the data retrieved from one call, to perform another call, and so on. Main thread AJAX call AJAX call AJAX call 42

Asynchronous calls These nested actions can become confusing with increasing functionality and other API-calls. Often referred to as callback hell $.getjson("https://api.chucknorris.io/jokes/random", function(data) { $("#norris_joke").text(data.value); $.getjson("some other api", function(data) { //do something with the data $.getjson("some other api", function(data) { //do something with this data also }); }); }); 43

Deferred and Promise To avoid this, we can use the jquery Deferred/ Promise. Promises are now also available in native JavaScript, but we will here use jquery. Bellow is a (very) simplified illustration $.getjson("url", function()) Deferred object Promise object allways() done() fail() state() then() 44

Deferred and Promise $.getjson("url", function()) Deferred object Promise object always() done() fail() state() then() $.getjson("https://api.chucknorris.io/jokes/random", function(data) { $("#norris_joke").text(data.value); }).then() { //do after resolve }); 45

Deferred and Promise $.getjson("https://api.chucknorris.io/jokes/random", function(data) { $("#norris_joke").text(data.value); }).then() { //new api-call }).then() { //new api-all }).then(){ hidewaitingscreen(); }); 46

Deferred and Promise function getrandomnorrisjoke() { return $.getjson("https://api.chucknorris.io/jokes/random"); } function displaynewjoke() { showwaitingscreen(); getrandomnorrisjoke().then(function(data) { $("#norris_joke").text(data.value); hidewaitingscreen(); }); } $("#get_joke").click(function() { displaynewjoke(); } 47