module 5 – django and git django web applica\on framework

27
1 - CSE 330 – Creative Programming and Rapid Prototyping Module 5 – JavaScript, AJAX, and jQuery Module 5 Contains an Individual and Group component – Both are due on Wednesday October 24 th – Start early on this module – One of the most time consuming modules in the course Read the WIKI before starting along with a few JavaScript and jQuery tutorials 2 - CSE 330 – Creative Programming and Rapid Prototyping Module 5 JavaScript – Scripting language to add interactivity to HTML pages – Java and JavaScript are completely different languages AJAX – Asynchronous JavaScript and XML (AJAX) – Allows for retrieval of data from web servers in the background jQuery – JavaScript library

Upload: others

Post on 12-Feb-2022

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 11 - CSE 330 – Creative Programming and Rapid Prototyping

Module5– JavaScript,AJAX,andjQuery

• Module5ContainsanIndividualandGroupcomponent– BotharedueonWednesdayOctober24th

– Startearlyonthismodule– Oneofthemosttimeconsumingmodulesinthecourse

• ReadtheWIKIbeforestartingalongwithafewJavaScriptandjQuerytutorials

Extensible Networking Platform 22 - CSE 330 – Creative Programming and Rapid Prototyping

Module5

• JavaScript– ScriptinglanguagetoaddinteractivitytoHTMLpages– JavaandJavaScriptarecompletelydifferentlanguages

• AJAX– AsynchronousJavaScriptandXML(AJAX)– Allowsforretrievalofdatafromwebserversinthebackground

• jQuery– JavaScriptlibrary

Page 2: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 33 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScript

• Popularscriptinglanguagewidelysupportedinbrowserstoaddinteraction– Pop-UpWindows– UserInputForms– Calculations– SpecialEffects

• ImplementationoftheECMAScriptlanguage

Extensible Networking Platform 44 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScript

• JavaScriptisaprototyped-basedscriptinglanguage– Dynamic,weaklytyped

• Interpretedlanguage– Youdonotcompileit

• Usesprototypesinsteadofclassesforinheritance

Page 3: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 55 - CSE 330 – Creative Programming and Rapid Prototyping

IsJavaScriptlikeJava?

• Java andJavaScriptaresimilarlikeCar andCarpetaresimilar

• Twocompletelydifferentlanguageswithdifferentconcepts– Javaiscompiled,JavaScriptisinterpreted– Javaisobject-oriented,JavaScriptisprototypedbased– Javarequiresstricttyping,JavaScriptallowsfordynamictyping

Extensible Networking Platform 66 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptBasics• Declareavariablewithlet

letfoo=“JSisfun”;

• Declareaconstantwithconstconst bar=”Thisiswillnotchange”;

• OlderversionsofJavaScriptdonotsupportletandconst andusevar instead– Inthiscoursewewilluselet andconst andavoidusingvar

• Defineafunctionwithfunctionfunction foo(){//SomeJScodehere

}

• Functionsarealsoobjects

Page 4: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 77 - CSE 330 – Creative Programming and Rapid Prototyping

WritingaJavaScriptProgram

• JavaScriptprogramscaneitherbeplaced– directlyintotheHTMLfileor– canbesavedinexternalfiles

• YoucanplaceJavaScriptanywherewithintheHTMLfile:within– the<HEAD>tagsor– the<BODY>tags

Extensible Networking Platform 88 - CSE 330 – Creative Programming and Rapid Prototyping

Usingthe<SCRIPT>Tag

<scriptsrc=“url”></script>– SRCpropertyisrequiredonlyifyouplaceyour

programinaseparatefile

<script>scriptcommandsandcomments

</script>

• OlderversionsofHTML(before5)useaslightlydifferentformat– <scripttype=“text/javascript”>– Thisisnolongernecessary,simplyuse<script>

Page 5: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 99 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptExample(part1)

<!DOCTYPEhtml><html><head><title>MyJavaScriptExample</title>

<script>function MsgBox(textstring){alert(textstring);

}

</script>

Extensible Networking Platform 1010 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptExample(part2)

<body><form><inputtype="text"name="text1"><inputtype="submit"value="ShowMe"onClick="MsgBox(form.text1.value)">

</form></body></html>

Page 6: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 1111 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptExample<!DOCTYPEhtml><htmllang="en"><head><title>MyJavaScriptExample</title>

<script>function MsgBox(textstring){alert(textstring);

}</script></head>

<body><form><inputtype="text"name="text1"><inputtype="submit"value="ShowMe"

onClick="MsgBox(form.text1.value)"></form></body></html>

Extensible Networking Platform 1212 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptEventListeners

• WecancontroleventsinamoregranularwayusingEventListeners

• EventListenersallowforcustombehaviorforeveryelement

document.getElementById("hello").addEventListener("click",MsgBox,false);

Page 7: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 1313 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptAdditionalInformation

• TheCSE330WikiprovidesagreatintrointoJavaScriptalongwithsomeexcellentlinkstomorecomprehensivetutorials

• AdditionalJStutorials– http://www.quirksmode.org/js/contents.html– https://docs.webplatform.org/wiki/Meta:javascript/tutorials

Extensible Networking Platform 1414 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptDebugging

• JSHint isagreatresourcestohelpdebugyourcode– http://www.jshint.com/

• Toolsforbrowsers also exist– Firefox

• Firebug extension– ChromeandSafari

• Webkit Inspector comes bundled withthebrowser

Page 8: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 1515 - CSE 330 – Creative Programming and Rapid Prototyping

JavaScriptExamples

http://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/

Extensible Networking Platform 1616 - CSE 330 – Creative Programming and Rapid Prototyping

AJAX

• Standsfor“AsynchronousJavaScriptandXML”

• Developmenttechniqueforcreatinginteractivewebapplications

• Notanew Technology butmoreofaPattern

Page 9: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 1717 - CSE 330 – Creative Programming and Rapid Prototyping

MotivationforAJAX

• WebpagesalwaysRELOADandnevergetUPDATED

• Userswaitfortheentirepagetoloadevenifasinglepieceofdataisneeded

• Singlerequest/responserestrictions

Extensible Networking Platform 1818 - CSE 330 – Creative Programming and Rapid Prototyping

Components

– HTML(orXHTML)andCSS• Presentinginformation

– DocumentObjectModel• Dynamicdisplayandinteractionwiththeinformation

– XMLHttpRequestobject• RetrievingdataASYNCHRONOUSLY fromthewebserver.

– JavaScript• Bindingeverythingtogether

Page 10: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 1919 - CSE 330 – Creative Programming and Rapid Prototyping

TheDOM

• DocumentObjectModel(DOM):platform- andlanguage-independentwaytorepresentXML– Adoptsatree-basedrepresentation– W3Cstandard,supportedbymodernbrowsers

• JavaScriptusesDOMtomanipulatecontent– Toprocessuserevents– Toprocessserverresponses(viaXMLHttpRequest)

Extensible Networking Platform 2020 - CSE 330 – Creative Programming and Rapid Prototyping

TheDOM

• Unlikeotherprogramminglanguages,JavaScriptunderstandsHTMLandcandirectlyaccessit

• JavaScriptusestheHTMLDocumentObjectModeltomanipulateHTML

• TheDOMisahierarchyofHTMLthings

• UsetheDOMtobuildan“address” torefertoHTMLelementsinawebpage

• LevelsoftheDOMaredot-separatedinthesyntax

Page 11: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 2121 - CSE 330 – Creative Programming and Rapid Prototyping

DOM

Extensible Networking Platform 2222 - CSE 330 – Creative Programming and Rapid Prototyping

AccessingtheDOMExample

https://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/

Page 12: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 2323 - CSE 330 – Creative Programming and Rapid Prototyping

WebApplicationandAJAX

Extensible Networking Platform 2424 - CSE 330 – Creative Programming and Rapid Prototyping

RequestProcessing

Page 13: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 2525 - CSE 330 – Creative Programming and Rapid Prototyping

Asynchronousprocessing- XMLHttpRequest

• AllowstoexecuteanHTTPrequestinbackground

• CallbackskickbackintoJavaScriptCode

• Supportedinallstandardbrowsers

Extensible Networking Platform 2626 - CSE 330 – Creative Programming and Rapid Prototyping

UsingXMLHttpRequest

• FirstyoumustcreatetheXMLHttpRequestObjectinJavaScript

• Example– constxmlHttp=newXMLHttpRequest();

• Olderbrowsersmightrequiredifferentsyntax– Forexample(InternetExplorerversions<9)

• constxmlHttp=newActiveXObject("Microsoft.XMLHTTP");– WewillnotworryaboutJScompatibilitywithIE<9inthiscourse

Page 14: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 2727 - CSE 330 – Creative Programming and Rapid Prototyping

UsingXMLHttpRequest

• TransferringdatatoServer– Open()toinitializeconnectiontoServer– Send()tosendtheactualData

• Example(POST)– xmlHttp.open("POST","/query.cgi”,true);– xmlHttp.send("name=Bob&[email protected]");

• Example(GET)– xmlHttp.open("GET","hello.txt",true);– xmlHttp.send(null);

Extensible Networking Platform 2828 - CSE 330 – Creative Programming and Rapid Prototyping

Whathappensaftersendingdata?

• XMLHttpRequestcontactstheserverandretrievesthedata– Cantakeindeterminateamountoftime

• CreateanEventListenertodeterminewhentheobjecthasfinishedloadingwiththedataweareinterestedin– Specificallylistenfortheloadeventtooccur

Page 15: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 2929 - CSE 330 – Creative Programming and Rapid Prototyping

Eventsofinterest

xmlHttp.addEventListener("load”,myCallbackFunction,false);

Extensible Networking Platform 3030 - CSE 330 – Creative Programming and Rapid Prototyping

UsingXMLHttpRequest

• Parseanddisplaydata– responseXML

• DOM-structuredobject– responseText

• Onecompletestring

• Examples– constnameNode=

requester.responseXML.getElementsByTagName("name")[0];

– constnameTextNode=nameNode.childNodes[0];

• Fromaneventfunction myCallback(event){alert(“Theresponse“ +event.target.responseText);}

Page 16: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 3131 - CSE 330 – Creative Programming and Rapid Prototyping

AJAXExample

<script>

constxmlHttp=newXMLHttpRequest();xmlHttp.open("GET","hello.txt",true);xmlHttp.addEventListener("load”,myCallback,false);xmlHttp.send(null);

function myCallback(event){alert(“Theresponse“ +event.target.responseText);}

</script>

Extensible Networking Platform 3232 - CSE 330 – Creative Programming and Rapid Prototyping

InteractionbetweenComponents

Page 17: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 3333 - CSE 330 – Creative Programming and Rapid Prototyping

AJAXExample

Extensible Networking Platform 3434 - CSE 330 – Creative Programming and Rapid Prototyping

Promises

• Apromiseisanobjectrepresentingtheeventualcompletion orfailure ofanasynchronousoperation

• Promisesarereturnedobjectsthatyouattachedcallbacksto

• Apromisecanonlysucceedorfail

• Thispromiseresolvestotheresponseofthatrequest,whetheritissuccessfulornot.

Page 18: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 3535 - CSE 330 – Creative Programming and Rapid Prototyping

CreatingandUsingPromises

• Thepromiseconstructortakesoneargument– Acallbackwithtwoparameters,resolveandreject.

const promise=newPromise(functionresolve,reject){

//dosomething

if(/*everythingworks*/){resolve("itworks");}else{reject(Error("Itdidnotwork"));

}});

• Toexecutethecallback:

promise.then(function(result){console.log(result);//worked},function(err){console.log(err);//Error:Itbroke

});

• Thethen()takestwoarguments– A callbackforsuccessandoneforfailure,bothareoptional.

Extensible Networking Platform 3636 - CSE 330 – Creative Programming and Rapid Prototyping

FetchAPI

• NewerAPIthatprovidesmechanismtoasynchronouslyaccessresourcesacrossthenetwork

• Fetchtakesoneargument– Thelinktotheresources

• Fetchreturnsapromise– WhichresolvestotheResponseObject

• SimilartoXMLHttpRequestbutwithafairlysimplesyntax

Page 19: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 3737 - CSE 330 – Creative Programming and Rapid Prototyping

FetchAPI• fetch()hasonerequiredargument(thepathtothe

resource)– Itreturnsapromise– Thispromiseresolvestotheresponseofthatrequest,whetheritissuccessfulornot.

fetch(url).then(function(response){//Dostuffwithresponse

}).catch(function(error){console.log("Foundanerror"+error);

});

Extensible Networking Platform 3838 - CSE 330 – Creative Programming and Rapid Prototyping

FetchExample

Page 20: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 3939 - CSE 330 – Creative Programming and Rapid Prototyping

AdditionalLinksforPromiseandFetch

• https://developers.google.com/web/fundamentals/primers/promises

• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

• https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Extensible Networking Platform 4040 - CSE 330 – Creative Programming and Rapid Prototyping

jQuery– SimplifyyourJavaScript

Page 21: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 4141 - CSE 330 – Creative Programming and Rapid Prototyping

WhatisjQuery?

• AframeworkforClientSideJavaScript

• Frameworksprovideusefulalternativesforcommonprogrammingtasks,creatingfunctionalitywhichmaynotbeavailableorcumbersometousewithinalanguage.

• Anopensourceproject,maintainedbyagroupofdevelopers,withaveryactivesupportbaseandthorough,wellwrittendocumentation.

Extensible Networking Platform 4242 - CSE 330 – Creative Programming and Rapid Prototyping

WhatjQueryisnot…

• AsubstituteforknowingJavaScript– jQueryisextraordinarilyuseful,butyoushouldstillknowhowJavaScriptworksandhowtouseitcorrectly.ThismeansmorethanGooglingatutorialandcallingyourselfanexpert.

• Asolveall– ThereisstillplentyoffunctionalitybuiltintoJavaScriptthatshouldbeutilized!Don’tturneveryprojectintoaquestto‘jQuery-ize’ theproblem,usejQuerywhereitmakessense.Createsolutionsinenvironmentswheretheybelong.

Page 22: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 4343 - CSE 330 – Creative Programming and Rapid Prototyping

WhatisavailablewithjQuery?

• Crossbrowsersupportanddetection

• AJAXfunctions• CSSfunctions• DOMmanipulation• DOMtransversal• Attributemanipulation• Eventdetectionandhandling

• JavaScriptanimation• Hundredsofpluginsforpre-builtuserinterfaces,advancedanimations,formvalidation,etc

• Expandablefunctionalityusingcustomplugins

• Smallfootprint

Extensible Networking Platform 4444 - CSE 330 – Creative Programming and Rapid Prototyping

ThejQuery/$Object

• Representedbyboth$andjQuery– TousejQuery only,usejQuery.noConflict(),forotherframeworksthatuse$

• Bydefault,$representsthejQuery object.Whencombinedwithaselector,canrepresentmultipleDOMElements

• UsedwithalljQuery functions.

Page 23: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 4545 - CSE 330 – Creative Programming and Rapid Prototyping

jQuery Examples

• jQuerybasicsyntax$(selector).action()

• $ signusedtoaccessjQuery• Selector “finds” theHTMLelement(s)• Anactionisperformedontheelement(s)

• Examples– $(this).hide()//hidescurrentelement– $(“p”).hide()//hidesall<p>elements– $(“.test”).hide()//hidesallelementswithclass=“test”– $(“#test”).hide()//hidestheelementwithid=“test”

Extensible Networking Platform 4646 - CSE 330 – Creative Programming and Rapid Prototyping

jQuery&AJAX

• jQuery hasaseriesoffunctionswhichprovideacommoninterfaceforAJAX,nomatterwhatbrowseryouareusing

• MostoftheupperlevelAJAXfunctionshaveacommonlayout:– $.func(url[,params][,callback]),[]optional

• url:stringrepresentingservertarget• params:namesandvaluestosendtoserver• callback:functionexecutedonsuccessfulcommunication.

Page 24: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 4747 - CSE 330 – Creative Programming and Rapid Prototyping

jQueryAJAXFunctions

• $.func(url[,params][,callback])– $.get– $.getJSON– $.getIfModified– $.getScript– $.post

• $(selector),injectHTML– load– loadIfModified

• $(selector),ajaxSetup alts– ajaxComplete– ajaxError– ajaxSend– ajaxStart– ajaxStop– ajaxSuccess

• $.ajax,$.ajaxSetup– async– beforeSend– complete– contentType– data– dataType– error– global– ifModified– processData– success– timeout– type– url

Extensible Networking Platform 4848 - CSE 330 – Creative Programming and Rapid Prototyping

Example– Show/Hidetheoldway

<ahref="#"onclick="toggle_visibility('foo');">Clickheretotogglevisibilityof#foo</a>

functiontoggle_visibility(id){conste=document.getElementById(id);if(e.style.display=='block')e.style.display='none';

elsee.style.display='block';

}

Page 25: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 4949 - CSE 330 – Creative Programming and Rapid Prototyping

Example– Show/HidewithjQuery

$().ready(function(){$("a").click(function(){

$("#more").toggle("slow");returnfalse;

});});

Extensible Networking Platform 5050 - CSE 330 – Creative Programming and Rapid Prototyping

Example– AjaxtheoldwayfunctionGetXmlHttpObject(handler){

letobjXmlHttp=null;//HoldsthelocalxmlHTTPobjectinstance

//Dependingonthebrowser,trytocreatethexmlHttpobjectif(is_ie){

varstrObjName=(is_ie5)?'Microsoft.XMLHTTP':'Msxml2.XMLHTTP';try{

objXmlHttp=newActiveXObject(strObjName);objXmlHttp.onreadystatechange=handler;

}catch(e){//Objectcreationerroredalert('VerifythatactivescriptingandactiveXcontrolsareenabled');return;}

}else{//Mozilla|Netscape|SafariobjXmlHttp=newXMLHttpRequest();objXmlHttp.onload=handler;objXmlHttp.onerror=handler;

}//ReturntheinstantiatedobjectreturnobjXmlHttp;

}

Page 26: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 5151 - CSE 330 – Creative Programming and Rapid Prototyping

Example– AjaxwithjQuery

$.get("update_actions.aspx",{st:"yes",f:$(this).attr("ID")});

Extensible Networking Platform 5252 - CSE 330 – Creative Programming and Rapid Prototyping

jQueryExamples

Page 27: Module 5 – Django and Git Django Web Applica\on Framework

Extensible Networking Platform 5353 - CSE 330 – Creative Programming and Rapid Prototyping

CalendarExamples