Download presentation
Presentation is loading. Please wait.
1
www.profburnett.com Master a Skill / Learn for Life
JavaScript & jQuery Session VI Chapter 12 - Ajax, JSON, and Flickr Master a Skill / Learn for Life
2
Class Outline What is Ajax? XMLHttpRequest (XHR) object GET or POST?
What is XML? What is JSON? What is JSONP? How to Use the HXR Object (XMLRequest Object) and JavaScript to Load XML data The jQuery Methods for Working with AJAX How to Use the jQuery $.ajax() Method for working with AJAX How to Use AJAX with Flickr Student Exercise 2/19/2019 © 2017, Profburnett.com
3
What is AJAX? AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously. Exchanging small amounts of data with the server Updates parts of a web page, without reloading the whole page. Examples of applications using AJAX: Google Maps, Gmail, YouTube, and Facebook. Google’s Auto Suggest is an Ajax application 2/19/2019 © 2017, Profburnett.com
4
HTTP Request 2/19/2019 © 2017, Profburnett.com
5
Ajax XMLHttpRequest 2/19/2019 © 2017, Profburnett.com
6
XMLHttpRequest (XHR) object
All modern browsers support the XMLHttpRequest object. Used to exchange data with a web server behind the scenes. Updates parts of a web page, without reloading the whole page. 2/19/2019 © 2017, Profburnett.com
7
XMLHttpRequest (XHR) object Methods
Description new XMLHttpRequest() Creates a new XMLHttpRequest Object abort() Cancels the current request getAllResponseHeaders() Returns header information getResponseHeader() Returns specific header information Open (method, url, async, user, psw) Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password 2/19/2019 © 2017, Profburnett.com
8
XMLHttpRequest (XHR) object Methods
Description send() Sends the request to the server Used for GET requests send(string) Sends the request to the server. Used for POST requests setRequestHeader() Adds a label/value pair to the header to be sent 2/19/2019 © 2017, Profburnett.com
9
XMLHttpRequest (XHR) object Properties
Property Description onreadystatechange Defines a function to be called when the readyState property changes readyState Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready responseText Returns the response data as a string responseXML Returns the response data as XML data 2/19/2019 © 2017, Profburnett.com
10
XMLHttpRequest (XHR) object Properties
Property Description status Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference statusText Returns the status-text (e.g. "OK" or "Not Found") 2/19/2019 © 2017, Profburnett.com
11
XMLHttpRequest (XHR) object Methods
Attribute Description name A name the can be referred to by client-side or server-side code. action The URL of the file that will process the data in the form. method Specifies the HTTP method (GET or POST) to be used when submitting the form data. “get” is default. 2/19/2019 © 2017, Profburnett.com
12
Common Data Formats for Ajax
Description Extension HTML Hypertext Markup Language html XM eXtensible Markup Language xml JSON JavaScript Object Notation json is often used 2/19/2019 © 2017, Profburnett.com
13
xhr.open('GET', 'shop.php?productID=34');
GET or POST? You can request and send data in several ways. The GET method requests information from a web server as part of the URL. The POST method sends data separately from the URL. You also use the open() method to specify the page on the server the data is sent to. xhr.open('GET', 'shop.php?productID=34'); 2/19/2019 © 2017, Profburnett.com
14
GET or POST Use Conventions
Use GET to get information. Use POST to change information: POST requires URL of programming process file (ASP, PHP) Request to delete data. Update database information. Insert new information. GET has limit on information sent because it is part of the URL, so use POST to post information. 2/19/2019 © 2017, Profburnett.com
15
Comparison of GET and POST
Resource GET POST BACK button/Reload Harmless Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted) Bookmarked Can be bookmarked Cannot be bookmarked Cached Can be cached Not cached Encoding type application/x-www-form-urlencoded application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data History Parameters remain in browser history Parameters are not saved in browser history Restrictions on data length Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) No restrictions Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also allowed Security GET is less secure compared to POST because data sent is part of the URL Never use GET when sending passwords or other sensitive information! POST is a little safer than GET because the parameters are not stored in browser history or in web server logs Visibility Data is visible to everyone in the URL Data is not displayed in the URL 2/19/2019 © 2017, Profburnett.com
16
Offsite open() method Request Issue
The URL you specify for the open() method must be on the same website as the page making the request. Web browsers won’t let you make Ajax requests to other domains. JSONP provides one way around this security problem. 2/19/2019 © 2017, Profburnett.com
17
What is XML? XML: Extensible Markup Language
A markup language and a metalanguage Markup language To design ways to describe information for storage, transmission, or processing Metalanguage To create a formal description of another language 8/1/2014 Copyright © Carl M. Burnett
18
XMLHttpRequest Object
XML Technologies Data Structure Metadata Stylization HTML Technologies XQuery XPointer XLink XPath XSLT XSL-FO XMLHttpRequest Object DTD XML XML Schema WSDL RSS XML-Namespaces 8/1/2014 Copyright © Carl M. Burnett
19
XML is not HTML Similarities Text-based Uses tags Uses attributes
Syntax is similar in appearance 2/19/2019 Copyright © Carl M. Burnett
20
XML is not HTML XML goal: HTML goal:
Describe data and to focus on what the data actually is Share richly structured electronic documents over the World Wide Web HTML goal: Display marked up content and apply default formatting 2/19/2019 Copyright © Carl M. Burnett
21
Comparing HTML and XML HTML XML
Finite number of tags with predefined semantics Used to display and format data XML Create own specific tags to meet own specific needs Used to structure and define the information Semantics are defined by applications that process it or by style sheets 2/19/2019 Copyright © Carl M. Burnett
22
Comparing HTML and XML documents
<p>ABC Co. owes us <strong>$3,17.89.</strong> This account should be monitored.</p> HTML Document <text> <client>ABC Co.</client> owes us <invant>$3,17.89</invant> <remark>This account should be monitored.</remark> </text> XML Document 2/19/2019 Copyright © Carl M. Burnett
23
XML Benefits XML removed 2 constraints from SGML and HTML
Dependence on inflexible document markup language (HTML) with predefined tags and semantics SGML is complex and allows many powerful options 2/19/2019 Copyright © Carl M. Burnett
24
XML Benefits Data interchange Extensibility Smart searches
Provides structure for storing data in text format, which can be used as a standard format for data interchange Extensibility Provides the ability to develop specific and unique tags Smart searches Provides high-precision searching in Web environments Granular updates Provides faster updates 2/19/2019 Copyright © Carl M. Burnett
25
XML-Based Languages Language Description CDF
Channel Definition Format – First real world application of XML (Microsoft Developed) CML Chemical Markup Language – Allows for the conversion of current files in structure documents and provide precise location of information in files. EIL Extensible Indexing Language – Looks at the tag in a document and assigns the content between the tags in a searchable fields. ETD-ML Electronic Thesis & Dissertation Markup Language – Converts theses from MS Word into SGML/XML. FlowML XML-based format for musical notation; a format for storing audio synthesis diagrams for synthesizers. ITML Information Technology Markup Language – Set of specification for protocols, message formats and best practices. 2/19/2019 Copyright © Carl M. Burnett
26
XML-Based Languages Language Description MathML
Mathematical Markup Language – Methodology for describing mathematical notations. SMIL Synchronized Multimedia Integration Language – Designed to integrate multimedia object into a synchronized presentation. VXML Voice Extensible Markup Language – Allow integration with the Internet through Voice-Recognition technology. XHTML HTML 4.01 written as an XML application. XSL Extensible Stylesheet Language – The style standard for XML documents. XSLT Extensible Stylesheet Language Transformation – Used to transform XML documents into other types of XML documents. 2/19/2019 Copyright © Carl M. Burnett
27
XML Rules Platform independent Software independent
Vendor and technology-independent metalanguage Designed to deliver structured content over the Web 2/19/2019 Copyright © Carl M. Burnett
28
XML Basic Components An element is the basic building block
Each element begins with a start tag and ends with an end tag Attributes are specifications for elements. They appear as name-value pairs Elements may or may not require attributes 8/1/2014 Copyright © Carl M. Burnett
29
XML Tree 8/1/2014 Copyright © Carl M. Burnett
Root Element <bookstore> Element <book> Element <Title> Attribute “lang” Text: Everyday Italian Element <Year> Text: 2005 Element <Author> Text: Giada De Laurentis Element <Price> Text: 30.00 Attribute <category> 8/1/2014 Copyright © Carl M. Burnett
30
XML Tree Root element = <bookstore>
<book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <price>29.99</price> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </bookstore> XML Tree Root element = <bookstore> All <book> elements in <bookstore> document 4 children: <title> <author> <year> <price> 8/1/2014 Copyright © Carl M. Burnett
31
XML Syntax Rules XML is case-sensitive Root Element is required
All opening tags must have a corresponding closing tag, or a terminating slash on opening tag No overlapping of tags can occur All attribute values must be enclosed in single or double quotation marks 8/1/2014 Copyright © Carl M. Burnett
32
XML Syntax Rules An application profile
Defines XML-related languages for a specific organization or industry Creates specific document types for XML-related languages and develops applications to handle those documents The tagged data can be used for creation, management, and maintenance of large collections of complex information 2/19/2019 Copyright © Carl M. Burnett
33
XML Elements Root Element Child Element Nesting Elements
<$xml version=“1.0”?> <bookstore> ……… </bookstore> Root Element Child Element Nesting Elements <$xml version=“1.0”?> <bookstore> <book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore> <$xml version=“1.0”?> <bookstore><title>Harry Potter</title></bookstore> 8/1/2014 Copyright © Carl M. Burnett
34
What is JSON? JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format JSON is language independent * JSON is "self-describing" and easy to understand
35
JSON Array Object Example
{ "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }
36
Much Unlike XML Because
JSON doesn't use end tag JSON is shorter JSON is quicker to read and write JSON can use arrays
37
JSON Syntax JSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays
38
JSON Data - A Name and a Value
"firstName" : "John" JSON values can be: A number (integer or floating point) A string (in double quotes) A Boolean (true or false) An array (in square brackets) An object (in curly braces) null
39
JSON Objects JSON Arrays {"firstName":"John", "lastName":"Doe"} {
"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }
40
JSON Uses JavaScript Syntax
{ "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } // returns John Doe employees[0].firstName + " " + employees[0].lastName;
41
JSON HTTP Request Example
1: Create an array of objects. 2: Create a JavaScript function to display the array. 3: Create a text file 4: Read the text file with an XMLHttpRequest HTTP Request Example
42
What is JSONP? JSONP (which stands for JSON with padding)
Technique to overcome: cross-domain restrictions imposed by browsers. allows data to be retrieved from foreign systems.
43
How JSONP it works Function call - myResponseFunction()
It is the "P" of JSONP (the "padding" around the pure JSON, or according to some the "prefix". myResponseFunction({"Name": "Foo", "Id": 1234, "Rank": 7});
44
How JSONP it works Server response that includes the JSONP function.
JSONP does not work with JSON-formatted results. The JSONP function invocation gets sent back The payload that the function receives, must be agreed-upon by the client and server. The browser provides the name of the callback function Named query parameter value - typically name “jsonp” or “callback” <script type="application/javascript" src=" </script>
45
Cross-domain requests using a proxy server
Newer browsers support CORS relax this constraint Cooperating proxy server does not have such restrictions Relays a browser request to a server in a separate domain Stores the result. Returns the JSON payload when the browser makes a second request. The xd_arbiter.php used by Facebook's JS SDK is a popular example of this cooperating server technique.[6]
46
Security Concerns Untrusted third-party code
Callback name manipulation and Reflected File Download Cross-site request forgery – (Exclusive use of cookies for determining if a request is authorized) Rosetta Flash - Adobe Flash Player (Fixed 2014)
47
How to Use the HXR Object (XMLRequest Object) and JavaScript to Load XML data
The Vecta Corp. Management Team HXR Object XMLRequest Object XML data (team.xml) 2/19/2019 © 2017, Profburnett.com
48
The jQuery Methods for Working with AJAX
Description load(url[,data][,success]) Loads HTML data. $.get(url[,data][,success[,dataType]) Loads data with GET request. $.post(url[,data][,success[,dataType]) Loads data with POST request. $.getJSON(url[,data][,success]) Loads JSON data with a GET request. 2/19/2019 © 2017, Profburnett.com
49
The jQuery Method Parameters for AJAX
Description url The string data A map or string sent to the server with the request. success A callback function that is executed if the request is successful. datatype The string that specifies the type of data (html, xml, json, or text) XML is Default The $each() jQuery Method for Processing data returned. Parameter Description $.each(collection, callback) The collection parameter object or array. The callback parameter is a function that is performed for each item in collection 2/19/2019 © 2017, Profburnett.com
50
Examples of Ajax methods
A load method $("#solution").load("solutions.html"); A $.get method $.get("getmanager.php", "name=agnes", showManager); A $.getJSON method $.getJSON("team.json", function(data){ // the statements for the success function } 2/19/2019 © 2017, Profburnett.com
51
How to Use jQuery load() Method for AJAX
Welcome to Vecta Corp. - Our Solutions jQuery load() Method to load HTML data 2/19/2019 © 2017, Profburnett.com
52
How to Use jQuery $.get() and $.post() Method to load XML data
Vecta Corp. Management Team - $.get() Vecta Corp. Management Team - $.post() Fails because of CORS 2/19/2019 © 2017, Profburnett.com
53
How to Use the the $.getJSON() Method to load JSON data
Vecta Corp. Management Team - $.getJSON() 2/19/2019 © 2017, Profburnett.com
54
How to Send Data with AJAX Request
A $.get method that uses a string for the data parameter $(document).ready(function() { $.get("getmanager.php", "name=wilbur", showManager); function showManager(data) { // process data } }); A $.get method that uses a map for the data parameter $(document).ready(function() { $.get("getmanager.php", {name:wilbur}, showManager); function showManager(data) { // process data } }); 2/19/2019 © 2017, Profburnett.com
55
How to Send Data with AJAX Request
The helper methods for working with Ajax Function Description serialize() Encode a set of form elements as a string used for a data parameter of AJAX request. serializeArray() Encode a set of form elements as an array of name/value pairs used for a data parameter of AJAX request. The HTML for a form <form id="contactForm"> <!-- the controls for the form --> </form> jQuery that uses the serialize method $(document).ready(function() { var formData = $("#contactForm").serialize(); $.get("processcontact.php", formData, processReturnedData); function processReturnedData(data) { // the statements for the success function } }); 2/19/2019 © 2017, Profburnett.com
56
How to Use the jQuery $.ajax() Method for working with AJAX
Syntax: $("button").click(function(){ $.ajax({url: "demo_test.txt", success: function(result){ $("#div1").html(result); }}); }); Changes the text of a <div> element using an AJAX request 2/19/2019 © 2017, Profburnett.com
57
jQuery $.ajax() Methods
Description $.ajax() Performs an async AJAX request $.ajaxPrefilter() Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax() $.ajaxSetup() Sets the default values for future AJAX requests $.ajaxTransport() Creates an object that handles the actual transmission of Ajax data $.get() Loads data from a server using an AJAX HTTP GET request $.getJSON() Loads JSON-encoded data from a server using a HTTP GET request $.parseJSON() Deprecated in version 3.0, use JSON.parse() instead. Takes a well-formed JSON string and returns the resulting JavaScript value $.getScript() Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request 2/19/2019 © 2017, Profburnett.com
58
jQuery $.ajax() Methods
Description $.param() Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests) $.post() Loads data from a server using an AJAX HTTP POST request ajaxComplete() Specifies a function to run when the AJAX request completes ajaxError() Specifies a function to run when the AJAX request completes with an error ajaxSend() Specifies a function to run before the AJAX request is sent ajaxStart() Specifies a function to run when the first AJAX request begins ajaxStop() Specifies a function to run when all AJAX requests have completed ajaxSuccess() Specifies a function to run when an AJAX request completes successfully 2/19/2019 © 2017, Profburnett.com
59
jQuery $.ajax() Methods
Description load() Loads data from a server and puts the returned data into the selected element serialize() Encodes a set of form elements as a string for submission serializeArray() Encodes a set of form elements as an array of names and values 2/19/2019 © 2017, Profburnett.com
60
jQuery $.ajax() Method Options
Syntax - $.ajax({name:value, name:value, ... }) Option Description async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true beforeSend(xhr) A function to run before the request is sent cache A Boolean value indicating whether the browser should cache the requested pages. Default is true complete(xhr,status) A function to run when the request is finished (after success and error functions) contentType The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded" context Specifies the "this" value for all AJAX related callback functions data Specifies data to be sent to the server 2/19/2019 © 2017, Profburnett.com
61
jQuery $.ajax() Method Options
Description dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest dataType The data type expected of the server response. error(xhr,status,error) A function to run if the request fails. global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false. jsonp A string overriding the callback function in a jsonp request jsonpCallback Specifies a name for the callback function in a jsonp request password Specifies a password to be used in an HTTP access authentication request. 2/19/2019 © 2017, Profburnett.com
62
jQuery $.ajax() Method Options
Description processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true success(result,status,xhr) A function to be run when the request succeeds timeout The local timeout (in milliseconds) for the request traditional A Boolean value specifying whether or not to use the traditional style of param serialization type Specifies the type of request. (GET or POST) url Specifies the URL to send the request to. Default is the current page username Specifies a username to be used in an HTTP access authentication request xhr A function used for creating the XMLHttpRequest object 2/19/2019 © 2017, Profburnett.com
63
How to Use the $.ajax() Method to load data
The Vecta Corp. Management Team (Error) The Vecta Corp. Management Team jQuery $.ajax() Method 2/19/2019 © 2017, Profburnett.com
64
How to Use AJAX with Flickr
2/19/2019 © 2017, Profburnett.com
65
Flickr Feeds Feed Description Public photos & video
The URL for the Flickr public feed documentation Feed Description Public photos & video Public content matching specified criteria. Friends photostream Public content from the contacts, friends, and family of a specified user. Public favorites from a user Public favorites for a specified user. Group discussions Recent discussions from a specified group. Group pools Items recently added to the pool of a specified group. Forum discussions Recent topics from the Flickr forum. Recent activity Recent activity for a specified user. Recent comments Recent comments by a specified user. 2/19/2019 © 2017, Profburnett.com
66
Public Photo Stream Common query parameters for the feed Parameter
The base URL for retrieving a public photo stream Common query parameters for the feed Parameter Description id A user id. ids A comma-delimited list of user ids. tags A comma-delimited list of tags that identify the photos. tagmode Controls whether the returned items must match all of the tags specified or any of the tags specified. The default is all. format The format of the returned feed. Atom 1.0 is the default. lang The display language of the feed. The default is English. jsoncallback Optional unless the return format is set to JSON. Then, this parameter must be coded as jsoncallback=? 2/19/2019 © 2017, Profburnett.com
67
Examples of URLs for JSON feeds (in one line)
For a specific user id and tag For all users and two tags &format=json&jsoncallback=?&tags=waterfall,yosemite 2/19/2019 © 2017, Profburnett.com
68
Data items returned by a photo feed
Description items The collection of returned items. title The title of the photo. link The URL for the Flickr page for the photo. media.m The URL for the photo. date_taken The date the photo was taken description Descriptive text for a photo, plus a thumbnail image in an <a> element that links to the full photo on the Flickr site. This data is formatted with HTML tags so it’s ready for display. published The date and time the photo was uploaded. author The author’s username and . author_id The author’s id. tags The filtering tags for a photo. 2/19/2019 © 2017, Profburnett.com
69
Flickr Feed Example 1 Feed from Website
Yosemite waterfalls jQuery code that gets Flickr titles and photos (Dreamweaver) The Flickr feed for the URL 2/19/2019 © 2017, Profburnett.com
70
Flickr Feed Example 2 Descriptions for Photo Feed
The Vecta Corp. Management Team jQuery code that gets Flickr description and photos (Dreamweaver) The Flickr feed for the URL 2/19/2019 © 2017, Profburnett.com
71
Flickr Feed Example 3 Search for Photos by Tags
Search by tags: yatch racing jQuery code to search by tag (Dreamweaver) The Flickr feed for the URL 2/19/2019 © 2017, Profburnett.com
72
Student Exercise Complete Chapter 12-1 Enhance Flickr Application on page 369 Create link to your Web4Students Webpage. Preview updated Web4Students Webpage. Post Chapter 12 Exercise and update Web4Students Webpage to Live site. 2/19/2019 Copyright 2017 © Carl M. Burnett
73
Class Review What is Ajax? XMLHttpRequest (XHR) object GET or POST?
What is XML? What is JSON? What is JSONP? How to Use the HXR Object (XMLRequest Object) and JavaScript to Load XML data The jQuery Methods for Working with AJAX How to Use the jQuery $.ajax() Method for working with AJAX How to Use AJAX with Flickr Student Exercise 2/19/2019 © 2017, Profburnett.com
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.