presentation 11
TRANSCRIPT
Unit 7: Ajax, JSON and API Essentials
Introduction to Ajax• Ajax is the acronym for Asynchronous JavaScript
and XML
• All moderns browsers provide an XMLHttpRequest object that is used to send an Ajax request to the web server and to receive the returned data from the server
• Ajax lets you receive data from a web server without reloading the page – “partial page refresh”
Normal HTTP RequestHow a normal HTTP request is processed
• Server returns an entire page for a normal HTTP request so the page has to be loaded into the browser
Application Server(Scripts)
Web Server Database Server
HTTP Request
HTTP Response(new page)
`
Web Browser
Ajax XMLHttpRequestHow an Ajax XMLHttpRequest is processed
• An Ajax request sends an XMLHttpRequest object to get data and the server returns only the data
• JavaScript is used to send the request, process the returned data and script the DOM with the new data
Application Server(Scripts)
Web Server Database Server
XMLHttpRequest
Response(Data only)
`
Web Browser(JavaScript)
Application Programming Interfaces
• Web sites like YouTube and Twitter provide Application Programming Interfaces (APIs) that show how to use Ajax to get data from their sites
• This means you can get data from these sites to enhance your web pages
Common FormatsFormat Description File extensionHTML Hypertext Markup
Languagehtml
XML eXtensible Markup Language
xml
JSON JavaScript Object Notation json
• XML is an open-standard, device-independent format that must be parsed by JavaScript or jQuery in the browser
• For the most part, JSON files are smaller and faster than XML
XML Data<?xml version="1.0" encoding="utf-8"?><management> <teammember> <name>Agnes</name> <title>Vice President of Accounting</title> <bio>With over 14 years of public accounting ... </bio> </teammember> <teammember> <name>Wilbur</name> <title>Founder and CEO</title> <bio>While Wilbur is the founder and CEO ... </bio> </teammember></management>
JSON Data{"teammembers":[ { "name":"Agnes", "title":"Vice President of Accounting", "bio":"With over 14 years of public accounting ..." }, { "name":"Wilbur", "title":"Founder and CEO", "bio":"While Wilbur is the founder and CEO ..." }]}
XMLHttpRequest ObjectMethod Descriptionabort() Cancels the current request.open(method,url[,async][,user][,pass])
Opens a connection for the request. The parameters let you set the method to GET or POST, set the URL for the request, set asynchronous mode to true or false and supply a username and password if authentication is required. When asynchronous is used, the application continues while the request is being processed.
send([data]) Starts the request. This method can include data that gets sent with the request. This method must be called after a request connection has been opened.
PropertyreadyState A numeric value that indicates the state of the current request: 0 is
UNSENT, 1 is OPENED, 2 is HEADERS_RECIEVED, 3 is LOADING and 4 is DONE
responseText The content that’s returned from the server in plain text format.Eventonreadystate An event that occurs when the state of the request changes.• A few more methods and properties in Figure 14-3 on pg. 441
jQuery Shorthand Methods for AjaxMethod Descriptionload(url[,data][,success]) Load HTML data.$.get(url[,data][,success][,dataType]) Load data with GET response.$.post(url[,data][,success[,dataType]) Load data with a POST request.$.getJSON(url[,data][,success]) Load JSON data with a GET
request.Parameter Descriptionurl The string for the URL to which the request is sent.data A map or string that is sent to the server with the
request, usually to filter the data that is returned.success A function that is executed if the request is
successful.dataType A string that specifies the type of data (html, xml,
json, script or text). The default is XML.
Examples of Ajax methodsA 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}
Load Method to Load HTML Data
• The load function can only load content from files on the same server as the page making the call.
<p>Which Vecta corp. solution are you interested in learning about?</p><a id=“vprospect” href=“#”>vProspect 2.0</a> |<a id =“vconvert” href=“#”>vConvert 2.0</a> |< a id=“vretain” href=“#”>vRetain 1.0</a><br><div id=“solution”></div>
Load HTML Data (con’t)The start of the second div element in the solutions.html file<div id="vconvert"> <p><strong>vConvert 2.0</strong></p> <p><img src="images/logo_vconvert.gif" width="63" height="36" > Create a highly user-friendly ... </p> <ul> <li>Build a visual and functional user ... </li> <li>Cause the desired emotional response ...</li> ... </ul></div>
The jQuery that loads the data$(document).ready(function() { $("#vprospect").click(function() { $("#solution").load("solutions.html #vprospect"); }); $("#vconvert").click(function() { $("#solution").load("solutions.html #vconvert"); }); $("#vretain").click(function() { $("#solution").load("solutions.html #vretain"); });});
$.get and $.post Method to Load XML
• To test these, the files must be on a web server
The HTML div element that receives the data<div id=“team”></div>
Load XML (con’t)The XML file (team.xml)<management> <teammember> <name>Agnes</name> <title>Vice President of Accounting</title> <bio>With over 14 years of public accounting ... </bio> </teammember> ...</management>
The jQuery$(document).ready(function(){ $.get("team.xml", function(data){ $("#team").html(""); $(data).find("management").children().each(function() { var xmlDoc = $(this); $("#team").append("<h3>" + xmlDoc.find("name").text() + "</h3>" + xmlDoc.find("title").text() + "<br>" + xmlDoc.find("bio").text() + "<br>"); }); });});
$.getJSON Method to Load JSON Data
The HTML div element that receives the data<div id=“team”></div>
Load JSON Data (con’t)The JSON file (team.json){"teammembers":[ { "name":"Agnes", "title":"Vice President of Accounting", "bio":"With over 14 years of public accounting... }, { "name":"Damon", "title":"Director of Development", "bio":"Damon is the Director of Development ... " }]}
The jQuery$(document).ready(function(){ $.getJSON("team.json", function(data){ $.each(data, function() { $.each(this, function(key, value) { $("#team").append( "Name: " + value.name + "<br>" + "Title: " + value.title + "<br>" + "Bio: " + value.bio + "<br><br>" ); }); }); });});
Send Data with an Ajax Request
• When you send data with an Ajax request, the URL is for a server-side script such as a PHP file. Then, the script is responsible for returning the data in XML or JSON format.
Two Ways to Send Data with Ajax
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 }});
Helper Methods for Working with Ajax
Function Descriptionserialize() Encode a set of form elements as a string that
can be used for the data parameter of an Ajax request.
serializeArray() Encode a set of form elements as an array of name/value pairs that can be used for the data parameter of an 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 }});
How to use $.ajax method for Working with Ajax
• The $.ajax method provides options that give you more control over the way the Ajax request works, such as providing a function for handling errors
• jqXHR object is jQuery’s superset of the standard XMLHttpRequest object that provides the properties of that object
• JSONP or “JSON with padding” is a complement to JSON data that lets you request data from a server in a different domain
Options for the $.ajax Method
Options Descriptionsurl The string for the URL to which the request is
sent.beforeSend(jqXHR, settings)
A function that is executed before the request is sent. It can pass two parameters: the jqXHR object and a map of the settings for this object.
cache A Boolean value that determines if the browser can cache the response.
data A map or string that is sent to the server with the request, usually to filter the data that is returned.
complete(jqXHR, status)
A function that is executed when the request finishes. It can receive two parameters: the jqXHR object and a string that represents the status of the request.
• More options in Figure 14-10 on pg. 425
$.ajax Method to Load DataThe HTML div element that receives the data<div id=“team”></div>
$.ajax Method (con’t)The XML file<management> <teammember> <name>Agnes</name> <title>Vice President of Accounting</title> <bio>With over 14 years of public accounting ... </bio> </teammember> ...</management>
$.ajax Method (con’t)The jQuery for the $.ajax Method$.ajax({ type: "get", url: "team.xml", beforeSend: function() { $("#team").html("Loading...");}, timeout: 10000, error: function(xhr, status, error) { alert("Error: " + xhr.status + " - " + error); dataType: "xml", success: function(data) { $("#team").html(""); $(data).find( "management").children().each(function() { var xmlDoc = $(this); $("#team").append("<h3>" + xmlDoc.find("name").text() + "</h3>" + xmlDoc.find("title").text() + "<br>" + xmlDoc.find("bio").text() + "<br>"); }); } });
Ajax with the API for Google’s Blogger
• Blogger is a free, Google application that lets you create your own blog
• All blogs are assigned a blog id that you must use along with your API key to get the JSON feed for your blog
• A blog consists of posts, comments, pages and users and the API documentation shows how to work with all of them
Online JSON Editor to Review Feed
• When the documentation for an API is difficult to understand, you can often save time by reviewing the data in the JSON feed for an application. That way, you can tell exactly what data your application is going to get.
• www.jsoneditoronline.org
Procedure for Reviewing a Feed
1. Type or paste the URL for the feed into the address bar of your browser. Then, press the Enter key to see the contents of the JSON feed in your browser window.
2. Copy all of the JSON, go to the URL for the online JSON editor (above) and paste the JSON into the left pane of the editor.
3. Click the Format button at the top of the left pane to see the formatted JSON data.
4. Click the right arrow button between the panes to see a structured version of the data. Then, click on Expand All button at the top of the right pane to see all of the data in the feed.
Ajax and JSON To Display Blogger Posts
<div id=“posts”></div>
Blogger (con’t)jQuery for Using Bloggervar apikey = ""; // set this to your API keyvar html = "";$.support.cors = true;$(document).ready(function() { $.ajax({ // the number in the url is the id for the blog url:"https://www.googleapis.com/blogger/v2/blogs/ 8698899267502010836/posts?key=" + apikey, dataType: "json", success: function(data) { $.each(data.items, function(index, value) { html += "<h3><a href='" + value.url + "'>" + value.title + "</a></h3>" + value.content + "<br>Posted by <a href='" + value.author.url + "'>" + value.author.displayName + "</a>"; }); // end each method $("#posts").html(html); } // end ajax options}); }); // end ajax and ready methods