Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | doncho-minkov |
View: | 5,601 times |
Download: | 1 times |
External Data External Data AccessAccess
With jQuery and AJAXWith jQuery and AJAX
Doncho MinkovDoncho Minkov
Telerik Mobile Development CourseTelerik Mobile Development Coursemobiledevcourse.telerik.com
Technical TrainerTechnical Trainerhttp://www.minkov.it
Table of ContentsTable of Contents RESTful Web ServicesRESTful Web Services XML, JSON, RSSXML, JSON, RSS Consuming REST with jQueryConsuming REST with jQuery Consuming Twitter REST with Consuming Twitter REST with
jQueryjQuery Twitter @AnywhereTwitter @Anywhere Twitter @Anywhere FeaturesTwitter @Anywhere Features Facebook APIFacebook API
RESTful Web RESTful Web ServicesServicesLightweight Architecture for Web Lightweight Architecture for Web
ServicesServices
What is REST?What is REST?
"Representational state transfer "Representational state transfer
(REST) is a style of software (REST) is a style of software
architecture for distributed architecture for distributed
hypermedia systems such as the World hypermedia systems such as the World
Wide Web."Wide Web."http://en.wikipedia.org/wiki/Representational_State_Transfer
Application state and functionality Application state and functionality are resources are resources
Every resource has an URIEvery resource has an URI All resources share a uniform All resources share a uniform
interfaceinterface This natively maps to the HTTP This natively maps to the HTTP
protocolprotocol
RESTful ServicesRESTful Services One URI for a resource, multiple One URI for a resource, multiple
operationsoperations Add a new document "RestTalk" in category Add a new document "RestTalk" in category
"Code""Code" PUT PUT http://mysite.com/docs/Code/RestTalk
Get the document / some pageGet the document / some page GET GET http://mysite.com/docs/Code/RestTalk://mysite.com/docs/Code/RestTalk
GET http://mysite.com/docs/Code/RestTalk/pages/3GET http://mysite.com/docs/Code/RestTalk/pages/3
Remove the documentRemove the document DELETE http://mysite.com/docs/Code/RestTalkDELETE http://mysite.com/docs/Code/RestTalk
Retrieve metadataRetrieve metadata HEAD http://mysite.com/docs/Code/RestTalkHEAD http://mysite.com/docs/Code/RestTalk
5
XML, JSON, RSSXML, JSON, RSSComparing the Common Service Data Comparing the Common Service Data
FormatsFormats
XMLXML XML is markup-language for XML is markup-language for
encoding documents in machine-encoding documents in machine-readable formreadable form Text-based formatText-based format
Consists of tags, attributes and Consists of tags, attributes and contentcontent
Provide data and meta-data in the Provide data and meta-data in the same timesame time
7
<?xml version="1.0"?><?xml version="1.0"?><library><library> <book><title>HTML 5</title><author>Bay <book><title>HTML 5</title><author>Bay Ivan</author></book>Ivan</author></book> <book><title>WPF <book><title>WPF 4</title><author>Microsoft</author></book>4</title><author>Microsoft</author></book> <book><title>WCF 4</title><author>Kaka <book><title>WCF 4</title><author>Kaka Mara</author></book>Mara</author></book> <book><title>UML 2.0</title><author>Bay <book><title>UML 2.0</title><author>Bay Ali</author></book>Ali</author></book></library></library>
JSONJSON JSON (JavaScript Object Notation)JSON (JavaScript Object Notation)
Standard for representing simple Standard for representing simple data structures and associative data structures and associative arraysarrays
Lightweight text-based open Lightweight text-based open standardstandard
Derived from the JavaScript Derived from the JavaScript language language
8
{{ "firstName": "John", "lastName": "Smith", "age": 25,"firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "33 Alex. Malinov Blvd.","address": { "streetAddress": "33 Alex. Malinov Blvd.", "city": "Sofia", "postalCode": "10021" },"city": "Sofia", "postalCode": "10021" }, "phoneNumber": [{ "type": "home", "number": "212 555-"phoneNumber": [{ "type": "home", "number": "212 555-1234"},1234"}, { "type": "fax", "number": "646 555-4567" }]{ "type": "fax", "number": "646 555-4567" }]},},{ "firstName": "Bay", "lastName": "Ivan", "age": 79 }{ "firstName": "Bay", "lastName": "Ivan", "age": 79 }
RSSRSS
RSS (Really Simple Syndication)RSS (Really Simple Syndication) Family of Web feed formats forFamily of Web feed formats for
publishing frequently updated workspublishing frequently updated works
E.g. blog entries, news headlines, videos, E.g. blog entries, news headlines, videos, etc.etc.
Based on XML, with standardized XSD Based on XML, with standardized XSD schemaschema
RSS documents (feeds) are list of itemsRSS documents (feeds) are list of items Each containing title, author, publish date, Each containing title, author, publish date,
summarized text, and metadatasummarized text, and metadata Atom protocol aimed to enhance / replace Atom protocol aimed to enhance / replace
RSSRSS 9
RSS – ExampleRSS – Example
10
<?xml version="1.0" encoding="utf-8" ?><?xml version="1.0" encoding="utf-8" ?><rss version="2.0"><rss version="2.0"><channel><channel> <title>W3Schools Home Page</title><title>W3Schools Home Page</title> <link>http://www.w3schools.com</link><link>http://www.w3schools.com</link> <description>Free web building tutorials</description><description>Free web building tutorials</description> <item><item> <title>RSS Tutorial</title><title>RSS Tutorial</title> <link>http://www.w3schools.com/rss</link><link>http://www.w3schools.com/rss</link> <description>New RSS tutorial on <description>New RSS tutorial on W3Schools</description>W3Schools</description> </item></item> <item><item> <title>XML Tutorial</title><title>XML Tutorial</title> <link>http://www.w3schools.com/xml</link><link>http://www.w3schools.com/xml</link> <description>New XML tutorial on <description>New XML tutorial on W3Schools</description>W3Schools</description> </item></item></channel></channel></rss></rss>
Consuming REST Consuming REST with jQuerywith jQuery
How To Make It Work?How To Make It Work?
Consuming REST With Consuming REST With jQueryjQuery
Can be done with three methodsCan be done with three methods $.ajax(…)$.ajax(…)
$.get(…)$.get(…)
$.post(…)$.post(…) $.get(…) $.get(…) and and $.post(…)$.post(…) use use
$.ajax(…)$.ajax(…) under the hood under the hood These methods load data from the These methods load data from the
serverserver Using rest serviceUsing rest service
Return JSON, Atom, RSSReturn JSON, Atom, RSS
Example of $.ajax(…)Example of $.ajax(…)
$.ajax({$.ajax({url: "RestService.svc/students/all",url: "RestService.svc/students/all",type: "GET", type: "GET", timeout: 5000, timeout: 5000, dataType: "json",dataType: "json",success: function (students) {success: function (students) {
$('#loadStudentsButton').html("students loaded");$('#loadStudentsButton').html("students loaded");// do something with the students data// do something with the students data// visualize them, etc…// visualize them, etc…
}} error: function (err) {error: function (err) { $('#loadStudentsButton').html("error: " + err.status);$('#loadStudentsButton').html("error: " + err.status); }}});});
The path of the REST The path of the REST ServiceService
(should be on the same (should be on the same server)server)
Request type ('GET' or Request type ('GET' or 'POST')'POST')
The type of data to The type of data to expect(JSON,XML)expect(JSON,XML)
In case the request is In case the request is successfulsuccessful
In case the request is In case the request is unsuccessfulunsuccessful
Example of Example of jQuery.ajax(…)jQuery.ajax(…) get get requestrequest
Example of $.ajax(…)Example of $.ajax(…)
$.ajax({$.ajax({url: "RestService.svc/students/new",url: "RestService.svc/students/new",type: "POST",type: "POST",timeout: 5000,timeout: 5000,contentType: "application/json",contentType: "application/json",data: JSON.stringify(student),data: JSON.stringify(student),success: function () {success: function () {
$('#createStudentButton').html("student created");$('#createStudentButton').html("student created");//reload the students//reload the students
},},error: function (err) {error: function (err) {
$('#createStudentButton').html("error: " + err.status);$('#createStudentButton').html("error: " + err.status);}}
});});
The type of The type of data to sent to data to sent to
the server the server (JSON, XML)(JSON, XML)
We have a student object (in We have a student object (in JSON) and should make it JSON) and should make it readable for the serverreadable for the server
Example of Example of jQuery.ajax(…) jQuery.ajax(…) post post requestrequest
Consuming Our REST Consuming Our REST
with jQuerywith jQueryLive DemoLive Demo
Consuming Twitter Consuming Twitter REST REST
with jQuerywith jQueryLets Make Our Own Twitter?Lets Make Our Own Twitter?
Twitter Rest APITwitter Rest API First lets get familiar with the First lets get familiar with the
Twitter REST APITwitter REST API We are given a set of methods toWe are given a set of methods to
Get a number of tweets for a given Get a number of tweets for a given useruser
Post a tweet using jQueryPost a tweet using jQuery
Search tweetsSearch tweets
Etc…Etc…
First need to register a twitter appFirst need to register a twitter app
Twitter Rest API (2)Twitter Rest API (2)
Registering a Twitter AppRegistering a Twitter App Go to http://dev.twitter.comGo to http://dev.twitter.com Register a AppRegister a App
When your app is registered you When your app is registered you get:get: Consumer keyConsumer key
The key your app authorizes withThe key your app authorizes with
Consumer secretConsumer secret Used for user authenticationUsed for user authentication
Methods of Twitter Methods of Twitter REST APIREST API
GET GET statuses/user_timelinestatuses/user_timeline Returns the 20 most recent statuses Returns the 20 most recent statuses
posted by the authenticating userposted by the authenticating user It is also possible to request another It is also possible to request another
user's timeline by using user's timeline by using The The screen_name screen_name or or user_id user_id parameterparameter
The other users timeline will only be The other users timeline will only be visible if they are not protectedvisible if they are not protected If the authenticating user's follow If the authenticating user's follow
request wasrequest was
Example of $.ajax(…)Example of $.ajax(…)
$.ajax({$.ajax({url : https://twitter.com/statuses/user_timeline/"+url : https://twitter.com/statuses/user_timeline/"+user+".json?callback=?"user+".json?callback=?"dataType : "json", dataType : "json", timeout:5000, timeout:5000, success : function(data) {success : function(data) {
//Visualize Tweets//Visualize Tweets},},error : function() { error : function() { //Visualize Errors//Visualize Errors}, },
}); });
Getting Getting TweetsTweets from from TwitterTwitter with with jQueryjQuery
TweetsTweetsLive DemoLive Demo
Twitter @AnywhereTwitter @AnywhereHow To Make It Easy?How To Make It Easy?
What is What is Twitter @AnywhereTwitter @Anywhere?? An easy-to-deploy solutionAn easy-to-deploy solution
Bringing the Twitter communication Bringing the Twitter communication platformplatform
Promotes a more engaged user Promotes a more engaged user basebase
Can be used to add Can be used to add FollowFollow ButtonsButtons, , HovercardsHovercards, , linkify linkify
TwitterTwitter usernamesusernames
Build integrations with "Build integrations with "Connect to Connect to TwitterTwitter""
Example of $.ajax(…)Example of $.ajax(…)
How to Use How to Use @Anywhere?@Anywhere?
With a registered App at With a registered App at dev.twitter.com dev.twitter.com You get a You get a AppIdAppId
In the In the headhead part of the app include part of the app include
With With anywhere.jsanywhere.js included included A A twttr twttr object and an object and an anywhereanywhere
functionfunction Used to make the magic with Used to make the magic with
anywhereanywhere
<script src="http://platform.twitter.com/<script src="http://platform.twitter.com/anywhere.js?id=YOUR_APP_ID&v=1"></script>anywhere.js?id=YOUR_APP_ID&v=1"></script>
@Anywhere Example@Anywhere ExampleLive DemosLive Demos
Search WidgetSearch Widget
new TWTR.Widget({new TWTR.Widget({ version: 2, type: 'version: 2, type: 'searchsearch', search: , interval: 300, ', search: , interval: 300, title: 'It\'s a double rainbow', subject: 'Across the sky',title: 'It\'s a double rainbow', subject: 'Across the sky', width: 250, height: 300, width: 250, height: 300, theme: {theme: {
shell: {background:'#shell: {background:'#70fd9070fd90',color: '#',color: '#000000000000'},'}, tweets: {background: '#tweets: {background: '#c6fec7c6fec7', color: '#', color: '#444444444444', links: ', links:
'#'#1985b51985b5'}'}},},features: {features: {
scrollbar: true,scrollbar: true,loop: true,loop: true,live: true,live: true,behavior: 'default'behavior: 'default'
}}}).render().start();}).render().start();
Tweets List WidgetTweets List Widget
new TWTR.Widget({new TWTR.Widget({ version: 2, type: 'version: 2, type: 'profileprofile', search: , interval: 300, ', search: , interval: 300, title: 'It\'s a double rainbow', subject: 'Across the sky',title: 'It\'s a double rainbow', subject: 'Across the sky', width: 250, height: 300, width: 250, height: 300, theme: {theme: {
shell: {background:'#shell: {background:'#70fd9070fd90',color: '#',color: '#000000000000'},'}, tweets: {background: '#tweets: {background: '#c6fec7c6fec7', color: '#', color: '#444444444444', links: ', links:
'#'#1985b51985b5'}'}},},features: {features: {
scrollbar: true,scrollbar: true,loop: true,loop: true,live: true,live: true,behavior: 'default'behavior: 'default'
}}}).render().start();}).render().start();
Twitter WidgetsTwitter WidgetsLive DemoLive Demo
Twitter @Anywhere Twitter @Anywhere FeaturesFeatures
Login/Logout, Tweet, etc.Login/Logout, Tweet, etc.
Login – LogoutLogin – Logout
twttr.anywhere(function (T) {twttr.anywhere(function (T) {T("#login").connectButton({T("#login").connectButton({ authComplete: function(user) {authComplete: function(user) {
//something to do after authentication//something to do after authentication },},});});
});});
Login:Login:
function logOut()function logOut(){{
twttr.anywhere.signOut();twttr.anywhere.signOut(); }}
LogoutLogout
Login/LogoutLogin/LogoutLive DemoLive Demo
FeaturesFeatures Tweet BoxTweet Boxtwttr.anywhere(function (T) {twttr.anywhere(function (T) { T("#tbox").tweetBox();T("#tbox").tweetBox();});});
Follow ButtonFollow Buttontwttr.anywhere(function (T) {twttr.anywhere(function (T) { T('#follow-T('#follow-donchominkov').followButton("donchominkov");donchominkov').followButton("donchominkov");}); });
Twitter @AnywhereTwitter @AnywhereLive DemoLive Demo
Facebook APIFacebook APILets Play a Little with FacebookLets Play a Little with Facebook
Facebook JavaScript Facebook JavaScript SDKSDK
Facebook provides a SDK for Facebook provides a SDK for JavaScriptJavaScript To use the functionality of FacebookTo use the functionality of Facebook
Should register an appShould register an app Through phone numberThrough phone number
With credit cardWith credit card
Absolutely freeAbsolutely free
Made for precautionsMade for precautions
Facebook APIFacebook APILive DemoLive Demo
QuestionsQuestions??
External Data AccessExternal Data Access