+ All Categories
Home > Education > 11. External Data Access - With jQuery and AJAX

11. External Data Access - With jQuery and AJAX

Date post: 19-Dec-2014
Category:
Upload: telerik-software-academy
View: 1,512 times
Download: 1 times
Share this document with a friend
Description:
Cross-Platform Mobile Development @ Telerik AcademyTelerik Software Academy: http://mobiledevcourse.telerik.comThe website and all video materials are in Bulgarian Content:RESTful Web ServicesXML, JSON, RSSConsuming REST with jQueryConsuming Twitter REST with jQueryTwitter @AnywhereTwitter @Anywhere FeaturesFacebook API
Popular Tags:
38
External Data Access With jQuery and AJAX Doncho Minkov Telerik Software Academy http://academy.telerik.com Technical Trainer http://minkov.it/ http://mobiledevcourse.telerik.com
Transcript
Page 1: 11. External Data Access - With jQuery and AJAX

External Data AccessWith jQuery and AJAX

Doncho Minkov

Telerik Software Academyhttp://academy.telerik.com

Technical Trainerhttp://minkov.it/

http://mobiledevcourse.telerik.com

Page 2: 11. External Data Access - With jQuery and AJAX

Table of Contents RESTful Web Services XML, JSON, RSS Consuming REST with jQuery Consuming Twitter REST with jQuery

Twitter @Anywhere Twitter @Anywhere Features Facebook API

Page 3: 11. External Data Access - With jQuery and AJAX

RESTful Web ServicesLightweight Architecture for Web

Services

Page 4: 11. External Data Access - With jQuery and AJAX

What is REST?

"Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web."http://en.wikipedia.org/wiki/Representational_State_Transfer

Application state and functionality are resources

Every resource has an URI All resources share a uniform

interface This natively maps to the HTTP

protocol

Page 5: 11. External Data Access - With jQuery and AJAX

RESTful Services One URI for a resource, multiple operations Add a new document "RestTalk" in

category "Code" PUT http://mysite.com/docs/Code/RestTalk

Get the document / some page GET http://mysite.com/docs/Code/RestTalk

GET http://mysite.com/docs/Code/RestTalk/pages/3

Remove the document DELETE http://

mysite.com/docs/Code/RestTalk

Retrieve metadata HEAD http://mysite.com/docs/Code/RestTalk

5

Page 6: 11. External Data Access - With jQuery and AJAX

XML, JSON, RSSComparing the Common Service Data

Formats

Page 7: 11. External Data Access - With jQuery and AJAX

XML XML is markup-language for encoding documents in machine-readable form Text-based format

Consists of tags, attributes and content

Provide data and meta-data in the same time

7

<?xml version="1.0"?><library> <book><title>HTML 5</title><author>Bay Ivan</author></book> <book><title>WPF 4</title><author>Microsoft</author></book> <book><title>WCF 4</title><author>Kaka Mara</author></book> <book><title>UML 2.0</title><author>Bay Ali</author></book></library>

Page 8: 11. External Data Access - With jQuery and AJAX

JSON JSON (JavaScript Object Notation)

Standard for representing simple data structures and associative arrays

Lightweight text-based open standard

Derived from the JavaScript language

8

{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "33 Alex. Malinov Blvd.", "city": "Sofia", "postalCode": "10021" }, "phoneNumber": [{ "type": "home", "number": "212 555-1234"}, { "type": "fax", "number": "646 555-4567" }]},{ "firstName": "Bay", "lastName": "Ivan", "age": 79 }

Page 9: 11. External Data Access - With jQuery and AJAX

RSS

RSS (Really Simple Syndication) Family of Web feed formats for

publishing frequently updated works E.g. blog entries, news headlines,

videos, etc.

Based on XML, with standardized XSD schema

RSS documents (feeds) are list of items Each containing title, author,

publish date, summarized text, and metadata

Atom protocol aimed to enhance / replace RSS

9

Page 10: 11. External Data Access - With jQuery and AJAX

RSS – Example

10

<?xml version="1.0" encoding="utf-8" ?><rss version="2.0"><channel> <title>W3Schools Home Page</title> <link>http://www.w3schools.com</link> <description>Free web building tutorials</description> <item> <title>RSS Tutorial</title> <link>http://www.w3schools.com/rss</link> <description>New RSS tutorial on W3Schools</description> </item> <item> <title>XML Tutorial</title> <link>http://www.w3schools.com/xml</link> <description>New XML tutorial on W3Schools</description> </item></channel></rss>

Page 11: 11. External Data Access - With jQuery and AJAX

Consuming REST with jQuery

How To Make It Work?

Page 12: 11. External Data Access - With jQuery and AJAX

Consuming REST With jQuery

Can be done with three methods $.ajax(…)

$.get(…)

$.post(…)

$.get(…) and $.post(…) use $.ajax(…) under the hood

These methods load data from the server Using rest service

Return JSON, Atom, RSS

Page 13: 11. External Data Access - With jQuery and AJAX

Example of $.ajax(…)

$.ajax({url: "RestService.svc/students/all",type: "GET", timeout: 5000, dataType: "json",success: function (students) {

$('#loadStudentsButton').html("students loaded");

// do something with the students data// visualize them, etc…

} error: function (err) { $('#loadStudentsButton').html("error: " + err.status); }});

The path of the REST Service(should be on the same

server)

Request type ('GET' or 'POST')

The type of data to expect(JSON,XML)

In case the request is successful

In case the request is unsuccessful

Example of jQuery.ajax(…) get request

Page 14: 11. External Data Access - With jQuery and AJAX

Example of $.ajax(…)

$.ajax({url: "RestService.svc/students/new",type: "POST",timeout: 5000,contentType: "application/json",data: JSON.stringify(student),success: function () {

$('#createStudentButton').html("student created");

//reload the students},error: function (err) {

$('#createStudentButton').html("error: " + err.status);

}});

The type of data to sent to

the server (JSON, XML)

We have a student object (in JSON) and should make it readable for the server

Example of jQuery.ajax(…) post request

Page 15: 11. External Data Access - With jQuery and AJAX

Consuming Our REST

with jQueryLive Demo

Page 16: 11. External Data Access - With jQuery and AJAX

Consuming Twitter REST

with jQueryLets Make Our Own Twitter?

Page 17: 11. External Data Access - With jQuery and AJAX

Twitter Rest API First lets get familiar with the Twitter REST API We are given a set of methods to

Get a number of tweets for a given user

Post a tweet using jQuery

Search tweets

Etc…

First need to register a twitter app

Page 18: 11. External Data Access - With jQuery and AJAX

Twitter Rest API (2) Registering a Twitter App

Go to http://dev.twitter.com Register a App

When your app is registered you get: Consumer key

The key your app authorizes with

Consumer secret Used for user authentication

Page 19: 11. External Data Access - With jQuery and AJAX

Methods of Twitter REST API

GET statuses/user_timeline Returns the 20 most recent

statuses posted by the authenticating user

It is also possible to request another user's timeline by using The screen_name or user_id

parameter

The other users timeline will only be visible if they are not protected If the authenticating user's follow

request was

Page 20: 11. External Data Access - With jQuery and AJAX

Example of $.ajax(…)

$.ajax({url : https://twitter.com/statuses/user_timeline/"+user+".json?callback=?"dataType : "json", timeout:5000, success : function(data) {

//Visualize Tweets},error : function() { //Visualize Errors},

});

Getting Tweets from Twitter with jQuery

Page 21: 11. External Data Access - With jQuery and AJAX

TweetsLive Demo

Page 22: 11. External Data Access - With jQuery and AJAX

Twitter @AnywhereHow To Make It Easy?

Page 23: 11. External Data Access - With jQuery and AJAX

What is Twitter @Anywhere? An easy-to-deploy solution

Bringing the Twitter communication platform

Promotes a more engaged user base

Can be used to add Follow Buttons, Hovercards, linkify

Twitter usernames

Build integrations with "Connect to Twitter"

Example of $.ajax(…)

Page 24: 11. External Data Access - With jQuery and AJAX

How to Use @Anywhere?

With a registered App at dev.twitter.com You get a AppId

In the head part of the app include

With anywhere.js included A twttr object and an anywhere

function Used to make the magic with

anywhere

<script src="http://platform.twitter.com/anywhere.js?id=YOUR_APP_ID&v=1"></script>

Page 25: 11. External Data Access - With jQuery and AJAX

@Anywhere ExampleLive Demos

Page 26: 11. External Data Access - With jQuery and AJAX

Search Widget

new TWTR.Widget({ version: 2, type: 'search', search: , interval: 300, title: 'It\'s a double rainbow', subject: 'Across the sky', width: 250, height: 300, theme: {

shell: {background:'#70fd90',color: '#000000'}, tweets: {background: '#c6fec7', color: '#444444', links:

'#1985b5'}},features: {

scrollbar: true,loop: true,live: true,behavior: 'default'

}}).render().start();

Page 27: 11. External Data Access - With jQuery and AJAX

Tweets List Widget

new TWTR.Widget({ version: 2, type: 'profile', search: , interval: 300, title: 'It\'s a double rainbow', subject: 'Across the sky', width: 250, height: 300, theme: {

shell: {background:'#70fd90',color: '#000000'}, tweets: {background: '#c6fec7', color: '#444444', links:

'#1985b5'}},features: {

scrollbar: true,loop: true,live: true,behavior: 'default'

}}).render().start();

Page 28: 11. External Data Access - With jQuery and AJAX

Twitter WidgetsLive Demo

Page 29: 11. External Data Access - With jQuery and AJAX

Twitter @Anywhere Features

Login/Logout, Tweet, etc.

Page 30: 11. External Data Access - With jQuery and AJAX

Login – Logout

twttr.anywhere(function (T) {T("#login").connectButton({ authComplete: function(user) {

//something to do after authentication

},});

});

Login:

function logOut(){

twttr.anywhere.signOut(); }

Logout

Page 31: 11. External Data Access - With jQuery and AJAX

Login/LogoutLive Demo

Page 32: 11. External Data Access - With jQuery and AJAX

Features

Tweet Boxtwttr.anywhere(function (T) { T("#tbox").tweetBox();});

Follow Buttontwttr.anywhere(function (T) { T('#follow-donchominkov').followButton("donchominkov");});

Page 33: 11. External Data Access - With jQuery and AJAX

Twitter @AnywhereLive Demo

Page 34: 11. External Data Access - With jQuery and AJAX

Facebook APILets Play a Little with Facebook

Page 35: 11. External Data Access - With jQuery and AJAX

Facebook JavaScript SDK

Facebook provides a SDK for JavaScript To use the functionality of Facebook

Should register an app Through phone number

With credit card

Absolutely free Made for precautions

Page 36: 11. External Data Access - With jQuery and AJAX

Facebook APILive Demo

Page 37: 11. External Data Access - With jQuery and AJAX

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

External Data Access

http://mobiledevcourse.telerik.com

Page 38: 11. External Data Access - With jQuery and AJAX

Free Trainings @ Telerik Academy

Cross-Platform Mobile Developmenthttp://mobiledevcourse.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com


Recommended