JavaScript, jQuery, and AJAX

CS418 - Web Programming - Spring 2015

Old Dominion University

Mat Kelly (mkelly@cs.odu.edu)
http://www.cs.odu.edu/~mkelly/cs418

What is JavaScript

  • "Language of the web browser"
    • means of interfacing with DOM
  • Large expressive power
  • Loosely typed
  • Powerful object literal notation (JSON)
  • Prototypical inheritance

Familiar syntax: Variables

  • Dynamically typed
    • var answer = "42";
    • var y = "The answer is "+answer;
  • JS tries to be smart, sometimes fails
    • console.log(answer - 1) returns "41"
    • console.log(answer + 1) returns "421"
  • Remedy with guidance on typing
  • var answer = 42;
  • console.log(answer - 1) returns 41
  • console.log(answer + 1) returns 40

Familiar syntax: Loops

  • for(var i=0; i<10; i++){...}
  • for(var myProp in myObject){...}
  • while(condition){...}
  • do {...} while(condition);

Familiar syntax: Conditionals

If, Else If, and Else
if(condition){
  ...
}else if(condition) {
  ...
}else {
  ...
}
  • Ternary Operator
  • var hill = age > 40 ? "Over" : "Under";
  • ...often difficult to parse, stick with ifs

Familiar syntax: try-catch

try {
  doSomething();
} catch (e){
  // Show errors here
} finally {
  // Always do this regardless of above
}

Familiar syntax: functions

  • definition

						function doSomething(theThing, maybeSomethingElseToo){
  ...
  return "some value!"
}
  • Invocation (all are valid):
doSomething("something","another");
doSomething("something");
doSomething("something","another","dance!");
function myOtherFunction(){
  console.log(arguments);
}
myOtherFunction("a","b"); produces ["a","b"];
  • Functions can be assigned to a variable and invoked later

						var foo = function(){console.log("bar");}
foo(); //produces "bar"

Familiar syntax: function hoisting

  • Functions can be called before declared

					foo();
function foo(){console.log("bar");
				
  • Function expressions cannot be called before declared

					foo(); //this will not work
var function(){console.log("bar");
				

Familiar syntax: Switch


var element = "Radon";

switch(element){
  case "Radon":
    console.log("86");
    break;
  case "Xenon":
    console.log("54");
    break;
  default:
    console.log("Unknown");
}
				

Objects

Literal definition

var m = {"a": 3, "b": 42, foo: function(){console.log(this.a);}};
m.foo(); //produces 3
					
Access using dot or bracket notation

m.b = "hello";
m['a'] = "world";
					

Object Protoyping

  • Class-free object system, objects inherit from objects
  • Behavior reduced (inheritance) performed as "decorating" existing objects

var User = function() {
  this.canLogin = true;
  this.value = 3;
}
User.prototype.login = function(){
  if(this.canLogin){console.log("User logging in");}
};
var Asker = function(id){
  User.call(this);
  this.id = id;
};
Asker.prototype = Object.create(User.prototype);
Asker.prototype.constructor = User;
Asker.prototype.login = function(){console.log("Asker logging in: "+this.value);};

var aUser = new User();
var anAsker = new Asker();

aUser.login();  // "User logging in"
anAsker.login();  // "Asker logging in: 3"
				

Namespaces

  • Global object
    • window in browsers
  • Sub-namespaces
    • window.document to access DOM in browser

Namespace Example


var MYFOO = MYFOO || {};
MYFOO.thingsToDo = {
  dance : function(el, type, fn){
    if(this.willing){
      console.log("Dancing!");
    }else {
      console.log("No!");
    }
  },
  makeWilling : function(el, type, fn){
    this.willing = true;
  },
  willing: false
};

var x = MYFOO.thingsToDo; //new MYFOO.thingsToDo(); would be invalid
x.dance();
x.makeWilling();
x.dance(); // x.sing() would yield UNDEFINED
MYFOO.thingsToDo.sing = function(){console.log("I don't sing");}
x.sing();
x.sing = function(){console.log("La la la!");}
x.sing();
			

JS in the browser: Waiting for the DOM

The DOM is accessible only once loaded
<html>
<head>


</head>
<body>
  

test

</body> </html>

JS in the browser: DOM-based trigger


<html>
<head>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
  console.log(document.getElementById('foo'));
});
</script>
</head>
<body>
  

test

</body> </html>

JS in the browser: DOM access

  • document.getElementById(id)
    • recall id is unique
  • document.getElementByClassName(className)
    • returns array of all elements match class
  • document.getElementById(id).getElementByClassName(className)
    • returns only children of element with id matching className
  • var myLink = document.getElementsByTagName("a")
  • myLink.href or myLink["href"]
  • myImage.src = "newImage.png"

JS Gotchas: Global Variables

  • Normally evil, required in JS (global)
  • Language provides workarounds
  • No linker (all compilation units in global object)
  1. var myVariables = myValue;
  2. window.myVariable = myValue;
    • window is the global variable in the browser
  3. myvariable = myValue
    • use variable without declaration

JS Gotchas: Scope

  • Block syntax but no block scope
    • variable declared in a block is visible everywhere in the containing function
  • best to declare variables at top of function
  • In most languages, variables should be declared on first use

JS Gotchas: Auto semi-colon

  • JS tries to best interpret malformed code
    • akin to HTML quirks mode
  • Sometimes this is detrimental:

return
  "foo";
...returns undefined

return "foo";
...returns "foo";

return
  ["2","3","4"];
...returns undefined

return ["2","3","4"]
or
return ["2",
 ["3","4"];
...returns ["2","3","4"];

JS Gotchas: reserved words

  • Certain words cannot be used in language for variables or parameters without special handling
abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while with

JS Gotchas: using reserved words

  • If used as keys for objects, they must be quotes
  • myObject[foo] is valid
  • myObject[case] is invalid
  • myObject["case"] is valid
  • myObject = {foo: 3}; is valid
  • myObject = {case: 3}; is invalid
  • myObject = {"case": 3} is valid
  • var foo is valid
  • var case is invalid
  • Reserved words cannot be used with dot notation
    • myObject.foo is valid
    • myObject.case is invalid
    • myObject."case" is invalid

More gotchas (see Appendix A of "JavaScript the Good Parts")

jQuery - basic information

  • library commonly used to simplify JS operations
  • overcomes some cross-browser compatibility issues
  • included local library in web page prior to utilizing

					<script src="jquery.js"></script>
<script>
...your jquery code...
</script>
				

jQuery - in the browser

  • $("#myLink") equivalent to document.getElementById('myLink');
  • $(".items") equivalent to document.getElementsByClassName('items');
  • Many DOM manipulation functions:
    • $("#myLink").css("color","red"); sets inline css, $("#myLink").css("color"); gets the already set value
    • $("#myLink").hide() removes change CSS of element to not be visible
    • $("#myLink").remove() removes element from DOM
  • Large API of DOM manipulation functions

AJAX

  • Asynchronous JavaScript And XML
  • Fetching content after the page has loaded
  • In JavaScript:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
   if (xhr.readyState == XMLHttpRequest.DONE ) {
      if(xhr.status == 200){
          document.getElementById("myText").innerHTML = xhr.responseText;
      }
      else if(xhr.status == 400) {  // HTTP status
         alert('Error 400')
      }
      else {
          alert('Something other than HTTP 200 returned')
      }
   }
}

xhr.open("GET", "anotherURI.html", true); //third value specs synchronicity
xhr.send();
					

AJAX - in jQuery

$.ajax({
    url: "anotherURI.html",
    done: function(response){
      $("myText").html(response);
    },
    fail: function() {...}
});
					

AJAX - an example


$.ajax({
    url: "changeThatValue.php",
    data: {"whichAttribute": thisAttribute, "toWhat": toThis},
    done: function(response){
      $("#myText").html(response);
    },
    fail: function() {...}
});
				

Code quality

  • JSLint - http://www.jslint.com/
  • JSHint - http://jshint.com/

Node.js

  • Server-side JavaScript
  • System independent of the browser
  • global score is not window
  • Intended for web services handling many asynchronous requests
  • JavaScript code not dependent on the DOM is portable to Node.js
  • Not going to be used in this class