AJAX and JSON with jQueryChen-Hsiang (Jones) n-jquery-examples.zippypj jjq yppJan. 5, 20106.4701

The goal of this lecture UnderstandUnderstandUnderstandUnderstandand know how to use AJAXJSONand know how to use jQuerythe usageg of AJAX and JSON with jQjQueryyjQueryJSONAJAXJan. 5, 20106.4702

Outline AJAX JSON jQueryJan. 5, 20106.4703

Prerequisites MIT SIPB Web Script Service mit edu/web/ Instructions:o Using any terminal to connect to Athenao athena% add scriptsathena% signup-webo Your web space will be at You can use any FTP client to upload your files and scripts FTP client: Filezilla (Windows/Linux/Mac)o ve: OpenAFS - 5, 20106.4704

AJAXJan. 5, 20106.4705

AJAX - 1 It stands for “Asynchronous JavaScript and XML” It was first mentioned by Jesse James Garrett in 2005. [1] It is not a new technology. It is several technologies. [1] standards-based presentation: XHTML and CSS dynamic display and interaction: DOM data interchange and manipulation: XML and XSLT asynchronous data retrieval: XMLHttpRequest binding everything together: JavaScriptJan. 5, 20106.4706

AJAX - 2 Intuition: Static web site vs. AJAX site AJAX engine: XMLHttpRequest object It allows for asynchronous communication Instead of freezing up until the completeness, the browser cancommunicate with server and continue as normal.Jan. 5, 20106.4707

AJAX - 3Figure: Traditional model vs. AJAX model [1]Jan. 5, 2010Figure: Synchronous interaction vs. Asynchronousinteraction [1]6.4708

AJAX - give up make embarrassedSQL QueryWeb BrowserdataDatabase1. mySQLScript Languages1 PHP1.Content:Ct t1. HTML Document2. XML Document3. JSON DocumentFigure: The process of AJAX callJan. 5, 20106.4709

AJAX - 5 POST and GET calls in AJAX [2] GET places arguments in the query string, but POST doesn’t. No noticeable difference in AJAX - AJAX request does notappear in the address bar. GET call in AJAX still has the size limitation on the amount of data thatcan be passed.passed General principle:o GET method: it is used to retrieve data to display in the page and thedata is not expected to be changed on the server.o POST method: it is used to updatepinformation on the server.Jan. 5, 20106.47010

Exercise: Example 1lettersABCabandonv./ give up make embarrassedletter GRE Word ListJan. 5, 20106.47011

?phpprint ' div class "entry" h3 class "term" ABANDON /h3 divdiv classclass "part" vpart v./n./n /div /div div class "definition" to give up completely /div /div div class "entry" h3 class "term" ABASH /h3 div class "part" v. /div div class "definition" to make embarrassed /div /div /div ';;? hpJan. 5, 20106.47012

html head link rel "stylesheet" href "example1.css" type "text/css"/ script type "text/javascript" AJAX – 6function sendRequest(url){Exampleajax1 ajaxCreate();if(!ajax){alert("Browser is not compatable with XMLHttpRequest");return 0;}var ajax;ffunctionti ajaxCreate(){j C t (){if(window.XMLHttpRequest){//For IE7 , Firefox, Chrome, Opera, Safarireturn new XMLHttpRequest();} else {//For IE6IE6, IE5return new ActiveXObject("Microsoft.XMLHTTP");}}function receiveData(){if(ajax.readyState 4){if(ajax.status 200){var content ML ajax.responseText;}else{alert("Server process error");}}}ajax.onreadystatechange receiveData;"GET", url, true);ajax.send(null);} /script /head body div class "letters" div class "letter" id "letter-a" h3 a href "javascript:sendRequest('example1.php')" A /a /h3 /div /div div id "content" /div /body /html htmlJan. 5, 20106.47013

AJAX - 5PropertiesDescription [3]onreadystatechangeygA JavaScriptp function objectjthat is called whenever the readyStateyattributechanges. The callback is called from the user interface thread.readyStateReturns values that indicate the current state of the object.ValueStateDescription0UNINITIALIZEDopen() has not been called yet.yet1LOADINGsend() has not been called yet.2LOADEDsend() has been called, and headers and status are available.3INTERACTIVEDownloading; responseText holds partial data.4COMPLETEDThe operation is complete.responseTextThe response to the request as text, or null if the request was unsucessful or hasnot yet been sent.responseXMLThe response to the request as a DOM Document object, or null if the request wasunsuccessful,ns ccessf l has not yetet been sent,sent oro cannot be parsedpa sed as XML.XML The responseesponse isparsed as if it were a text/xml stream.statusThe status of the response to the request. This is the HTTP result code (forexample, status is 200 for a successful request).statusTextThe response string returned by the HTTP server. Unlike status, this includes theentire text of the response message ("200 OK", for example).Jan. 5, 20106.47014

AJAX - 6MethodsDescription [3]Abort()Aborts the request if it has already been sent.getAllResponseHeaders()Returns all the response headers as a string.getResponseHeader("headerLabel")Returns the text of a specified method , "URL"[open("method"URL [,asyncFlag[, "userName"[,"password"]]])Initializes a request. This method is to be used from JavaScript code;to initialize a request from native code, use openRequest() instead.send(content)()Sends the request. If the request is asynchronous (which is thedefault), this method returns as soon as the request is sent. If therequest is synchronous,synchronous this method doesndoesn'tt return until the responsehas arrived.setRequestHeader("label", "value")Sets the value of an HTTP request header.Jan. 5, 20106.47015

Jan. 5, 20106.47016

JSONJan. 5, 20106.47017

JSON - 1 Text is a data transmission format on the Internet A need to transmit complicated (structured) data Book info, movie info, etc. Idea: Encode data Transmit in text format Decode dataJan. 5, 20106.47018

JSON - 2 It stands for “JavaScript Object Notation” and it is a textbbaseddddatat iinterchangethfformat.t [4] JSON is built on two structures: jA collection of name and value ppairsObject:Array: An ordered list of valuesFigure: The diagrams of the syntax of JSON [3]Jan. 5, 20106.47019

Explanationobject with one memberobject with two members(separated by a comma)array with 3 elementsExamples{}{}"course-name": "6.470“"course-name":"coursename": "6"6.470",470""units": 6["foo", "bar", 12345]{object with an array as a value}{objects with objects and arrays}"course-name": "6.470","times": ["12-4","12-4", "12-4"]"John":John 78]]}Concrete Examples [5]Jan. 5, 20106.47020

JSON - 3 Examples:{}{"course-name” : "6.470”["foo", "bar", 12345]}"course-name” : "6.470","times": ["12-4","12-4", "12-4"]Figure: The diagrams of the syntax of JSON [4]Jan. 5, 20106.47021

JSON - 4"data":[[1880data :[[1880,0.081536],[1881,0.08098],[1882,0.078308]]0 081536] [1881 0 08098] [1882 0 078308]]Figure: The diagrams of the syntax of JSON [4]Jan. 5, 20106.47022

JSON - 5 Why JSON format is easier to be evaluated?var a {} Jan. 5, ":"James"label : James 8278]]}To get the value 1880 marked with red color:o We can use[0][0]6.47023

Exercise: Example 2lettersABCabandonv./ give up make embarrassedletterJan. 5, 2010 6.47024

Example 2: Extending Example 1 script type "text/javascript" function receiveData(){(){if(ajax.readyState 4){if(ajax.status 200){var data [{ "word":"ABANDON","function":"vfunction : v./n./n ","definition":"to give up completely"},{ "word":"ABASH","function":"v.","definition":"to make embarrassed"}];Wh t isWhati theth problem?bl ?var content ML data;}else{alert("Server process error");}}example2.html} /script Jan. 5, 2010http://chyu scripts mit edu/example2 25

Wh t isWhati theth problem?bl ?Jan. 5, 20106.47026

script type "text/javascript" function receiveData(){if( jif(ajax.readyStated St t 4){if(ajax.status 200){var data [{ todefinition : to give up completely"}completely },{ "word":"ABASH","function":"v.","definition":"to make embarrassed"}];var output "";for(each in data){output ' div class "entry" ';output ' h3 class "word" ' data[each].word ' /h3 ';output ' div class "function" ' data[each].function ' /div ';outputt t ' div' di class "definition" 'l"d fi iti " ' ddata[each].definitiont [h] d fi iti '' /div ';/di 'output ' /div ';}var content document.getElementById('content');content innerHTML output;content.innerHTML}else{alert("Server process error");}}} /script Jan. 5, example2-sol.html6.47027

Jan. 5, 20106.47028

jQueryquery ? query ? query ? query ? query ? query ? query ? query ? query ? query ? query ? query ? query ?Jan. 5, 20106.47029

jQuery - 1 JavaScript libraries and frameworks Prototype, jQuery, Dojo, Echo, GWT, MooTools, Rico, YUI, etc. Advantages Providing common utilities Handling cross-platform issues (Might) provide extendibility - plugins Faster Web developmentJan. 5, 20106.47030

jQuery - 2 jQuery: A JavaScript library was released by John Resig in 2006 Idea: Putting together a set of functions Navigate a document Event handling Select DOM elements Create animations Ajax development Extendibility: plugins It is used at 21% of the 10000 most popular websites. [6]Jan. 5, 20106.47031

jQuery - 3 Usage: Step 1: Download the latest jQuery from Step 2: Link the downloaded .js file- script type “text/javascript” src “jquery-1.3.2.js” /script - Note: It adds jQuery() function in the global namespace and thefunction is also aliased as (). () Step 3: Write your codeJan. 5, 20106.47032

jQuery - 4 APIs: jQuery SSEEventstEffectsAjaxUtilitiUtilitiesjQuery UIJan. 5, 20106.47033

jQuery - 5 APIs: jQuery SSEEventstEffectsAjaxUtilitiUtilitiesjQuery UIJan. 5, 20106.47034

jQuery - 6 Core: jQuery functions:o (expression, [context]) (‘input:radio’, document.form[0])o (html) (' div (' di idid “loading" Loading. /div ')“l di " L di/di ')o (elements) (document.body).css(‘background’, (document body) css(‘background’ ‘red’);o (callback)The same as (document).ready() (function(){alert( (function(){alert(“test”);})test );})Jan. 5, 20106.47035

jQuery - 7 Selectors: No matter which type of selectors, we start with (). jQuery supports nearly all selectors in CSS 1 through 3. Types:o Basic: element,lt #id#id, class,l.classA.classBlA lB Ex: (‘p’), (‘#id’), (‘.class’), (‘.classA.classB’)o Hierarchy: ancestor decendent, parent child, prev next Ex: ( (‘formform inputinput’)), ( (‘#main#main *’)), (‘label ( label input’)input )Jan. 5, 20106.47036

jQuery - 8o Form:SelectorsMatched Elements:inputinput, select, textarea and button elements:text, :radio, :checkbox, :image,:submit :reset:submit,:reset, :password:password, :fileinput element with attribute that is equal to the specifiedselectors:buttonbutton element, input element with type is “button”o Basic filters: :first , :last , :not(selector) , :even , :odd , :eq(index) ,:gt(index) , :lt(index) , :header , :animatedo Attribute filters: [attribute] , [attribute! value] , [attribute value] ,[attribute value] , [attribute* value], [filter1][filter2]Jan. 5, 20106.47037

jQuery - 9 Attributes: Attr:o attr(name), attr(properties) attr(key,value), removeAttr(name)Class:o addClass(class), removeClass(class), toggleClass(class)HTML:o html(), html(value)Text:o text(), text(value)Value:o val(), val(value)Jan. 5, 20106.47038

jQuery - 10 Events: Page load:l do ready(fn)Event handling:o bind(type, fn), unbind(type, fn), trigger(event)Event helpers:o click(), click(fn), mousedown(fn), mouseout(fn), Effects: Basics:o show(),show() show(speed)show(speed), hide(),hide() toggle(),toggle() toggle(speed)Fading:o fadeIn(speed), fadeOut(speed), fadeTo(speed, opacity)Jan. 5, 20106.47039

Exercise: Example 3contentA SCANDAL IN BOHEMIAI.FFF Please use example3.htmlTo Sherlock Holmes she is always THE woman. I haveseldom heard him mention her under any other name. Inhis eyes she eclipses and predominates the whole of hersex. It was not that he felt any emotion akin to love forIrene Adler. All emotions, and that one particularly, wereabhorrent to his cold. Requirement:o Using jQuery selectors, attributes, eventso When clicking font symbols (small, medium,large) the content of paragraphs can changelarge),properly.II.At three o'clock precisely I was at Baker Street, butHolmes had not yet returned. The landlady informed methat he had left the house shortly after eight o'clock inthe morning. .o Set default font size of the content ofparagraphs as .edu/example3.htmlJan. 5, 20106.47040

Exercise: Example 3 - reference solution script type "text/javascript" (document).ready(function(){ ('#large').bind(‘click’, function(){ ('p').removeClass().addClass('large');}); ('#medium').bind(‘click’, function(){ ('p').removeClass().addClass('medium');}); ('#small').bind(‘click’, function(){ ('p').removeClass().addClass('small');});// Set default font size as medium ('#medium').trigger('click');});example3-sol.htmlp /script Jan. 5, .47041

Exercise: Example 3The content was from [7].Jan. 5, 20106.47042

jQuery - 11 Ajax: Ajax Request:o .ajax(options) options: a set of key/value pairso .get(url, [data], [callback], [type])o .post(url, [data], [callback], [type])o .getJSON(url, [data], [callback], [type])o .getScript(url, [callback]) .ajax({url: “process.php",type: "POST",data: “class 6470&name Tim",class 6470&name Tim ,success: function(msg){alert(“Data:" msg );}}));Jan. 5, 2010 .post( post("test.php",{func: alert(data.time);},"json“json);6.47043

jQuery - 12 ds/photos public.gne?tags doggy&format json&jsoncallback ?",function(data){ each(data items function(i,item){ .each(data.items,f nction(i item){ (" img/ ").attr("src","#images");if ( i 2 ) return false;});});Jan. 5, 20106.47044

jQuery - 13 Ajax Events:o ajaxComplete(callback), ajaxStart(callback), ajaxStop(callback),ajaxSend(callback), ajaxError(callback), ajaxSuccess(callback)o Ex: (' div (div id "loading" Loading. /div ')id loading Loading. /div ).insertBefore("#images").ajaxStart((){function(){ (this).show();}j).ajaxStop(function(){ (this).hide();});Jan. 5, 20106.47045

Exercise: Example 4a.b.c.abandonv./ give up make embarrassedJan. 5, 20106.47046

Exercise: Example 4 ?phpJan. 5, 2010 data '[{"word": "ABANDON","function": "v./n.","definition": "to give up completely"},{"word": "ABASH","function": "v.","definition": "to make embarrassed"},{"word": "ABATE","function": "v.","definition": "to make less in amount; wane"},{"word": "ABBREVIATE","function": "v.","definition": "to make shorter; to shorten a word or xample4.php';print( GET['callback'].'('. data.')');? 6.47047

Example 4: Using jQuery for example 1 script type "text/javascript" (document).ready(function(){()y(()var url "example4.php";Part 1 ('#letter-a').click(function(){1stparameter2nd parameter .getJSON(urll '?'?callback ?',llb k ?'function(data){ ('#content').empty(); .each(data, function(index, entry){var html ' div class "entry" ';html ' h3 h3 classclass "word" 'word entry[entry['word']word ] ' /h3 '; /h3 ;html ' div class "function" ' entry['function'] ' /div ';html ' div class "definition" ' entry['definition'] ' /div ';html ' /div '; ('#content').fadeIn().append(html);});});return false;}); }); /script Jan. 5, le4.html6.47048

Example 4: Using jQuery for example 1 script type type "text/javascript" text/javascript (document).ready(function(){ Part 2// Slide up or down the function and definition of the word ('.word').live('click', function(){ s('.definition').slideToggle();}); ('#showDetails').click(function(){ ngs('.definition').show('slow');}); ('#hideDetails').click(function(){ ngs('.definition').hide('slow');});}); /script Chaining the ample4.htmlJan. 5, 20106.47049

Example 4: Using jQuery for example 1 script type "text/javascript" (document).ready(function(){var url "example4.php"; ('#letter-a').click(function(){ .getJSON(url '?callback ?', function(data){ ('#content').empty(); .each(data, function(index, entry){var html ' div class "entry" ';html ' h3 class "word" ' entry['word'] ' /h3 ';html ' div div classclass "function" 'function entry[entry['function']function ] ' /div '; /div ;html ' div class "definition" ' entry['definition'] ' /div ';html ' /div '; ('#content').fadeIn().append(html);});});return false;;});Complete Version// Slide up or down the function and definition of the word ('.word').live('click', function(){ s('.definition').slideToggle();}); ('#showDetails').click(function(){ ngs('.definition').show('slow');}); ('#hideDetails').click(function(){ ('.word ide(hide('slow')slow (hide('slow');slow );});}); /script example4.htmlJan. 5, 20106.47050

Jan. 5, 20106.47051

References[1] Ajax: A New Approach to Web ays/archives/000385.php[2] AJAX - GetG t or PPost.t t //ji t b t/ d/ j / / jht[3] Mozilla XMLHttpRequest.[4] Introducing JSON.[5] 6.470 2009 IAP - AJAX with jQuery.[[6]] Websites usingg jQjQuery,y, ordered byy popularity.p py ////jQy[7] Project Gutenberg - The Adventures of Sherlock Holmes.[8] Jonathan Chaffer and Karl Swedberg, Learning jQuery 1.3, PACKT publishing, 2009. Lecture Slides: jquery slides.pdf Lecture Examples Sol: les sol.zipJan. 5, 20106.47052