Module 5 JavaScript, AJAX, and jquery Module 5 Contains 2 components Both the Individual and Group portion are due on Monday October 30 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 Extensible Networking Platform 1 1 - 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 Extensible Networking Platform 2 2 - CSE 330 Creative Programming and Rapid Prototyping
JavaScript Popular scripting language widely supported in browsers to add interaction Pop-Up Windows User Input Forms Calculations Special Effects Implementation of the ECMAScript language Extensible Networking Platform 3 3 - CSE 330 Creative Programming and Rapid Prototyping JavaScript JavaScript is a prototyped-based scripting language Dynamic, weakly typed Interpreted language You do not compile it Uses prototypes instead of classes for inheritance Extensible Networking Platform 4 4 - CSE 330 Creative Programming and Rapid Prototyping
Is JavaScript like Java? Java and JavaScript are similar like Car and Carpet are similar Two completely different languages with different concepts Java is compiled, JavaScript is interpreted Java is object-oriented, JavaScript is prototyped based Java requires strict typing, JavaScript allows for dynamic typing Extensible Networking Platform 5 5 - CSE 330 Creative Programming and Rapid Prototyping JavaScript Basics Declare a variable with var var foo = JS is fun ; Variables are objects Define a function with function function foo() { //Some JS code here } Functions are also objects Extensible Networking Platform 6 6 - CSE 330 Creative Programming and Rapid Prototyping
Writing a JavaScript Program JavaScript programs can either be placed directly into the HTML file or can be saved in external files You can place JavaScript anywhere within the HTML file: within the <HEAD> tags or the <BODY> tags Extensible Networking Platform 7 7 - CSE 330 Creative Programming and Rapid Prototyping Using the <SCRIPT> Tag <script src= url ></script> SRC property is required only if you place your program in a separate file <script> script commands and comments </script> Older versions of HTML (before 5) used a slightly different format <script type= text/javascript > This is no longer necessary, simply use <script> Extensible Networking Platform 8 8 - CSE 330 Creative Programming and Rapid Prototyping
JavaScript Example (part 1) <!DOCTYPE html> <html> <head><title>my JavaScript Example</title> <script> function MsgBox(textstring) { alert(textstring); } </script> Extensible Networking Platform 9 9 - CSE 330 Creative Programming and Rapid Prototyping JavaScript Example (part 2) <body> <form> <INPUT NAME="text1" TYPE=Text> <INPUT NAME="submit" TYPE=Button VALUE="Show Me" onclick="msgbox(form.text1.value) > </form> </body> </html> Extensible Networking Platform 10 10 - CSE 330 Creative Programming and Rapid Prototyping
JavaScript Example <!DOCTYPE html> <html> <head><title>my JavaScript Example</title> <script> function MsgBox(textstring) { alert(textstring); } </script> </head> <body> <form> <INPUT NAME="text1" TYPE=Text> <INPUT NAME="submit" TYPE=Button VALUE="Show Me" onclick="msgbox(form.text1.value) > </form> </body> </html> Extensible Networking Platform 11 11 - CSE 330 Creative Programming and Rapid Prototyping JavaScript Event Listeners We can control events in a more granular way using Event Listeners Event Listeners allow for custom behavior for every element document.getelementbyid("hello").addeventlistener("click",msgbox, false); Extensible Networking Platform 12 12 - CSE 330 Creative Programming and Rapid Prototyping
JavaScript Additional Information The CSE 330 Wiki provides a great intro into JavaScript along with some excellent links to more comprehensive tutorials Additional JS tutorials http://www.quirksmode.org/js/contents.html https://docs.webplatform.org/wiki/meta:javascript/t utorials Extensible Networking Platform 13 13 - CSE 330 Creative Programming and Rapid Prototyping JavaScript Debugging JSHint is a great resources to help debug your code http://www.jshint.com/ Tools for browsers also exist Firefox Firebug extension Chrome and Safari WebkitInspector comes bundled with the browser Extensible Networking Platform 14 14 - CSE 330 Creative Programming and Rapid Prototyping
JavaScript Examples http://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/ Extensible Networking Platform 15 15 - CSE 330 Creative Programming and Rapid Prototyping AJAX Stands for Asynchronous JavaScript and XML Development technique for creating interactive web applications Not a new Technology but more of a Pattern Extensible Networking Platform 16 16 - CSE 330 Creative Programming and Rapid Prototyping
Motivation for AJAX Web pages always RELOAD and never get UPDATED Users wait for the entire page to load even if a single piece of data is needed Single request/response restrictions Extensible Networking Platform 17 17 - CSE 330 Creative Programming and Rapid Prototyping Components HTML (or XHTML) and CSS Presenting information Document Object Model Dynamic display and interaction with the information XMLHttpRequest object Retrieving data ASYNCHRONOUSLY from the web server. Javascript Binding everything together Extensible Networking Platform 18 18 - CSE 330 Creative Programming and Rapid Prototyping
The DOM Document Object Model (DOM): platform- and language-independent way to represent XML Adopts a tree-based representation W3C standard, supported by modern browsers JavaScript uses DOM to manipulate content To process user events To process server responses (via XMLHttpRequest) Extensible Networking Platform 19 19 - CSE 330 Creative Programming and Rapid Prototyping The DOM Unlike other programming languages, JavaScript understands HTML and can directly access it JavaScript uses the HTML Document Object Model to manipulate HTML The DOM is a hierarchy of HTML things Use the DOM to build an address to refer to HTML elements in a web page Levels of the DOM are dot-separated in the syntax Extensible Networking Platform 20 20 - CSE 330 Creative Programming and Rapid Prototyping
DOM Extensible Networking Platform 21 21 - CSE 330 Creative Programming and Rapid Prototyping Accessing the DOM Example https://research.engineering.wustl.edu/~todd/cse330/demo/lecture5/ Extensible Networking Platform 22 22 - CSE 330 Creative Programming and Rapid Prototyping
Web Application and AJAX Extensible Networking Platform 23 23 - CSE 330 Creative Programming and Rapid Prototyping Request Processing Extensible Networking Platform 24 24 - CSE 330 Creative Programming and Rapid Prototyping
Asynchronous processing - XMLHttpRequest Allows to execute an HTTP request in background Callbacks kick back into Javascript Code Supported in all standard browsers Extensible Networking Platform 25 25 - CSE 330 Creative Programming and Rapid Prototyping Using XMLHttpRequest First you must create the XMLHttpRequest Object in JavaScript Example var xmlhttp = new XMLHttpRequest(); Older browsers might require different syntax For example (Internet Explorer versions <9) var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); We will not worry about JS compatibility with IE < 9 in this course Extensible Networking Platform 26 26 - CSE 330 Creative Programming and Rapid Prototyping
Using XMLHttpRequest Transferring data to Server Open() to initialize connection to Server Send() to send the actual Data Example (POST) xmlhttp.open("post", "/query.cgi,true); xmlhttp.send("name=bob&email=bob@example.com"); Example (GET) xmlhttp.open("get","hello.txt",true); xmlhttp.send(null); Extensible Networking Platform 27 27 - CSE 330 Creative Programming and Rapid Prototyping What happens after sending data? XMLHttpRequest contacts the server and retrieves the data Can take indeterminate amount of time Create an Event Listener to determine when the object has finished loading with the data we are interested in Specifically listen for the load event to occur Extensible Networking Platform 28 28 - CSE 330 Creative Programming and Rapid Prototyping
Events of interest xmlhttp.addeventlistener("load,mycallbackfunction,false); Extensible Networking Platform 29 29 - CSE 330 Creative Programming and Rapid Prototyping Using XMLHttpRequest Parse and display data responsexml DOM-structured object responsetext One complete string Examples var namenode = requester.responsexml.getelementsbytagname("name")[0]; var nametextnode = namenode.childnodes[0]; From an event function mycallback(event) { alert( The response + event.target.responsetext); } Extensible Networking Platform 30 30 - CSE 330 Creative Programming and Rapid Prototyping
AJAX Example <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.open("get","hello.txt",true); xmlhttp.addeventlistener("load,mycallback,false); xmlhttp.send(null); function mycallback(event) { alert( The response + event.target.responsetext); } </script> Extensible Networking Platform 31 31 - CSE 330 Creative Programming and Rapid Prototyping Interaction between Components Extensible Networking Platform 32 32 - CSE 330 Creative Programming and Rapid Prototyping
AJAX Example Extensible Networking Platform 33 33 - CSE 330 Creative Programming and Rapid Prototyping jquery Simplify your JavaScript Extensible Networking Platform 34 34 - CSE 330 Creative Programming and Rapid Prototyping
What is jquery? A framework for Client Side JavaScript Frameworks provide useful alternatives for common programming tasks, creating functionality which may not be available or cumbersome to use within a language. An open source project, maintained by a group of developers, with a very active support base and thorough, well written documentation. Extensible Networking Platform 35 35 - CSE 330 Creative Programming and Rapid Prototyping What jquery is not A substitute for knowing JavaScript jquery is extraordinarily useful, but you should still know how JavaScript works and how to use it correctly. This means more than Googling a tutorial and calling yourself an expert. A solve all There is still plenty of functionality built into JavaScript that should be utilized! Don t turn every project into a quest to jquery-ize the problem, use jquery where it makes sense. Create solutions in environments where they belong. Extensible Networking Platform 36 36 - CSE 330 Creative Programming and Rapid Prototyping
What is available with jquery? Cross browser support and detection AJAX functions CSS functions DOM manipulation DOM transversal Attribute manipulation Event detection and handling JavaScript animation Hundreds of plugins for pre-built user interfaces, advanced animations, form validation, etc Expandable functionality using custom plugins Small foot print Extensible Networking Platform 37 37 - CSE 330 Creative Programming and Rapid Prototyping The jquery/$ Object Represented by both $ and jquery To use jquery only, use jquery.noconflict(), for other frameworks that use $ By default,$ represents the jquery object. When combined with a selector, can represent multiple DOM Elements Used with all jquery functions. Extensible Networking Platform 38 38 - CSE 330 Creative Programming and Rapid Prototyping
jquery basic syntax $(selector).action() jquery Examples $ sign used to access jquery Selector finds the HTML element(s) An action is performed on the element(s) Examples $(this).hide() //hides current element $( p ).hide() //hides all <p> elements $(.test ).hide() //hides all elements with class= test $( #test ).hide() //hides the element with id= test Extensible Networking Platform 39 39 - CSE 330 Creative Programming and Rapid Prototyping jquery & AJAX jquery has a series of functions which provide a common interface for AJAX, no matter what browser you are using Most of the upper level AJAX functions have a common layout: $.func(url[,params][,callback]), [ ] optional url: string representing server target params: names and values to send to server callback: function executed on successful communication. Extensible Networking Platform 40 40 - CSE 330 Creative Programming and Rapid Prototyping
jquery AJAX Functions $.func(url[,params][,callback]) $.get $.getjson $.getifmodified $.getscript $.post $(selector), inject HTML 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 41 41 - CSE 330 Creative Programming and Rapid Prototyping Example Show/Hide the old way <a href="#" onclick="toggle_visibility('foo');">click here to toggle visibility of #foo</a> function toggle_visibility(id) { var e = document.getelementbyid(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } Extensible Networking Platform 42 42 - CSE 330 Creative Programming and Rapid Prototyping
Example Show/Hide with jquery $().ready(function(){ $("a").click(function(){ $("#more").toggle("slow"); return false; }); }); Extensible Networking Platform 43 43 - CSE 330 Creative Programming and Rapid Prototyping Example Ajax the old way function GetXmlHttpObject(handler) { var objxmlhttp = null; //Holds the local xmlhttp object instance } //Depending on the browser, try to create the xmlhttp object if (is_ie){ var strobjname = (is_ie5)? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; try{ objxmlhttp = new ActiveXObject(strObjName); objxmlhttp.onreadystatechange = handler; } catch(e){ //Object creation errored alert('verify that activescripting and activex controls are enabled'); return; } } else{ // Mozilla Netscape Safari objxmlhttp = new XMLHttpRequest(); objxmlhttp.onload = handler; objxmlhttp.onerror = handler; } //Return the instantiated object return objxmlhttp; Extensible Networking Platform 44 44 - CSE 330 Creative Programming and Rapid Prototyping
Example Ajax with jquery $.get("update_actions.aspx", {st: "yes", f: $(this).attr("id")} ); Extensible Networking Platform 45 45 - CSE 330 Creative Programming and Rapid Prototyping jquery Examples Extensible Networking Platform 46 46 - CSE 330 Creative Programming and Rapid Prototyping
Calendar Examples Extensible Networking Platform 47 47 - CSE 330 Creative Programming and Rapid Prototyping