With jQuery and AJAX Doncho Minkov Telerik Corporation Technical Trainer
RESTful Web Services XML, JSON, RSS Consuming REST with jQuery Consuming Twitter REST with jQuery Features Facebook API
Lightweight Architecture for Web Services
"Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web." Application state and functionality are resources Every resource has an URI All resources share a uniform interface This natively maps to the HTTP protocol
One URI for a resource, multiple operations Add a new document "RestTalk" in category "Code" PUT Get the document / some page GET GET Remove the document DELETE Retrieve metadata HEAD 5
Comparing the Common Service Data Formats
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 <library> HTML 5 Bay Ivan HTML 5 Bay Ivan WPF 4 Microsoft WPF 4 Microsoft WCF 4 Kaka Mara WCF 4 Kaka Mara UML 2.0 Bay Ali UML 2.0 Bay Ali </library>
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, "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": " "}, "phoneNumber": [{ "type": "home", "number": " "}, { "type": "fax", "number": " " }] { "type": "fax", "number": " " }]}, { "firstName": "Bay", "lastName": "Ivan", "age": 79 }
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
10 <channel> W3Schools Home Page W3Schools Home Page Free web building tutorials Free web building tutorials RSS Tutorial RSS Tutorial New RSS tutorial on W3Schools New RSS tutorial on W3Schools XML Tutorial XML Tutorial New XML tutorial on W3Schools New XML tutorial on W3Schools </channel></rss>
How To Make It Work?
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
$.ajax({ url: "RestService.svc/students/all", type: "GET", timeout: 5000, dataType: "json", success: function (students) { $('#loadStudentsButton').html("students loaded"); $('#loadStudentsButton').html("students loaded"); // do something with the students data // visualize them, etc… } error: function (err) { error: function (err) { $('#loadStudentsButton').html("error: " + err.status); $('#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
$.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
Live Demo
Lets Make Our Own Twitter?
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
Registering a Twitter App Go to Register a App When your app is registered you get: Consumer key The key your app authorizes with Consumer secret Used for user authentication
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
$.ajax({ url : user+".json?callback=?" dataType : "json", timeout:5000, success : function(data) { //Visualize Tweets }, error : function() { //Visualize Errors //Visualize Errors},}); Getting Tweets from Twitter with jQuery
Live Demo
How To Make It Easy?
What is 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"
With a registered App at dev.twitter.com 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
Live Demos
new TWTR.Widget({ version: 2, type: 'search', search:, interval: 300, version: 2, type: 'search', 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:'# 70fd90 ',color: '# '}, shell: {background:'# 70fd90 ',color: '# '}, tweets: {background: '# c6fec7 ', color: '# ', links: '# 1985b5 '} tweets: {background: '# c6fec7 ', color: '# ', links: '# 1985b5 '}}, features: { scrollbar: true, loop: true, live: true, behavior: 'default' }}).render().start();
new TWTR.Widget({ version: 2, type: 'profile', search:, interval: 300, version: 2, type: 'profile', 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:'# 70fd90 ',color: '# '}, shell: {background:'# 70fd90 ',color: '# '}, tweets: {background: '# c6fec7 ', color: '# ', links: '# 1985b5 '} tweets: {background: '# c6fec7 ', color: '# ', links: '# 1985b5 '}}, features: { scrollbar: true, loop: true, live: true, behavior: 'default' }}).render().start();
Live Demo
Login/Logout, Tweet, etc.
twttr.anywhere(function (T) { T("#login").connectButton({ authComplete: function(user) { authComplete: function(user) { //something to do after authentication }, },});}); Login: function logOut() { twttr.anywhere.signOut(); twttr.anywhere.signOut(); } Logout
Live Demo
Tweet Box twttr.anywhere(function (T) { T("#tbox").tweetBox(); T("#tbox").tweetBox();}); Follow Button twttr.anywhere(function (T) { T('#follow-donchominkov').followButton("donchominkov"); T('#follow-donchominkov').followButton("donchominkov");});
Live Demo
Lets Play a Little with Facebook
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
Live Demo
Questions?