JavaScript

From CSE330 Wiki
Revision as of 08:20, 10 September 2012 by Shane (talk | contribs) (Updating Article and Adding Content)
Jump to navigationJump to search

JavaScript is the most widely used scripting language for implementing client-side functionality in Web applications. Unlike PHP, JavaScript code is interpreted and executed in a client's web browser (not on the web server).

JavaScript? Did you mean Java?

JavaScript is a prototype-based programming language focussed on web interactivity. It was first introduced in Netscape Navigator, and it in turn gave rise to what is now ECMAScript. Originally, JavaScript was called "LiveScript". Sun, the developer of Java at the time, wanted a language that would complement its compiled Java language, and so LiveScript was renamed JavaScript.

Beyond that, Java and JavaScript are as similar as Ham and Hamster.

Java and JavaScript have similar syntax, but the under workings are quite different. For example, Java requires strict typing, but JavaScript allows for dynamic typing. Java is object-oriented, but JavaScript is prototype-oriented. Java is compiled, but JavaScript is interpreted.

JavaScript Language Components

This section highlights some features of the JavaScript language that differentiate it from other languages. For a more comprehensive JavaScript tutorial, the following tutorials are both high quality:

Variables and Scope

To define a variable in JavaScript, use the var keyword.

var foo = "bar";

Notice that like PHP, you do not have to define a type like int or string; this is because JavaScript and PHP are dynamically typed languages.

JavaScript code can access any variable higher in the “function tree”, but not vice-versa. This is called scope. All functions create their own scope.

When you reference a variable, JavaScript will look up through the "function tree" until it finds the variable you asked for. This means that you could define variables of the same name as global variables inside of functions. For demonstration of concept:

var a = "hello";
var b = "world";

function sayGoodByeWorld(){
	var a = "goodbye";

	alert(a); // goodbye
	alert(b); // world
}

sayGoodByeWorld();

alert(a); // hello

Functions

To define a function in JavaScript, use the function keyword.

function sayHello(){
	alert("Hello World");
}

sayHello(); // call the function

Pass a parameter to a function like this:

function sayHello(name){
	alert("Hello, "+name);
}

sayHello("Todd"); // call the function and pass an argument

In JavaScript, functions are objects. This means that they can be assigned to variables, manipulated on the fly, and even passed as parameters! As we will see in a couple sections, this is an extremely important feature of JavaScript that makes it such a robust language for web development.

If you want to define a scope-specific function, you can assign it to a variable like this:

var sayHello = function(){
	alert("Hello World");
}

sayHello(); // call the function

Closures

A closure is a way to separate a certain snippet of JavaScript code from the global scope. This is useful if you do not want to "muck up" global variables. Closures are essentially anonymous functions that are called as soon as they are created:

var a = "hello";

(​​​​function(){
	var b = "world";
	
	alert(a); // hello
	alert(b); // world
})();

alert(a); // hello
alert(b); // ReferenceError: b is not defined​​​​​​​​​​​​​​​

Most JavaScript libraries (like jQuery) write all of their code in a closure. What this means is that except for one or two variable names (jQuery or $), everything associated with the library is completely self-contained.

Document Object Model

The Document Object Model (DOM) is what enables JavaScript to manipulate the content of your web page.

More Info

Since the javascript code runs in the web browser, you'll have to use web browser tools for all debugging. Generally speaking, if you have syntax or runtime errors in your javascript, the web browser will report nothing but not attempt to run the script. So if it appears that your code is doing nothing, then it's likely a syntax error of some sort. Fortunately, in Firefox, you can use the error console to view warnings and errors produced as javascripts are executed. Go to Tools->Error Console to access it. This is most useful for simple syntatic debugging. If you need a more serious debugger, you can use Firebug for Firefox.

Asynchronous Javascript And XML

AJAX, Asynchronous Javascript And XML, is a group of related web development techniques, standards, and technologies used on the client (web browser) side of the standard web server-client communication model. Although other languages can be used, the most common is to use javascript to send asynchronous requests to the web server in order to retrieve XML data that the javascript then uses to produce dynamic, fast, user-friendly web pages. The key idea is that a large fraction of the work happens at the web browser, and larger requests happen behind the scenes, keeping waiting times for data to come back over the network to a minimum. AJAX is generally also associated with higher-level APIs and libraries that aid in producing cleaner user interfaces for web applications.

The javascript XMLHttpRequest object is used to exchange data with the web servers without needing to reload the entire web page in the browser. This XMLHttpRequest object is now supported by all major browsers, although some browsers implement support in slightly different ways, leading to different behavior of the same code on different platforms. For this course, you should focus on supporting Firefox, but in any real production website it's very important to do validation testing using all of the major browsers including Firefox, Internet Explorer, Safari, and Opera as a minimum.

XMLHttpRequest Object

The XMLHttpRequest object handles communication with the web servers. To use it, you must first initialize a variable to be an instance of the XMLHttpRequest class.

 var xmlHttp;
 xmlHttp=new XMLHttpRequest();

Once you have an XMLHttpRequest, you can use it to send requests to a server. Initially, you need to connect to the server side page you are interested in:

xmlHttp.open("METHOD","REMOTE_URL", ASYNCRONOUS_FLAG);

where METHOD is "GET" or "POST", REMOTE_URL is the page that you are going to send requests to, and ASYNCRONOUS_FLAG is true or false to indicate whether the calls should be made asynchronously or synchronously. In asynchronous communication, the client can do other things while waiting for the server response, whereas in synchronous communication, the client blocks execution and waits until the response comes back before proceeding. Once the object has been opened, you can then use the send method to send a request to the server. Note that you do not explicitly set data fields to send, because it is contained in the URL request.

xmlHttp.send(null);

The XMLHttpRequest object has an attribute, readyState, that stores the current state of the request.

StateDescription
0The request is not initialized
1The request has been set up
2The request has been sent
3The request is in process
4The request is complete

For example, when a request is sent, the state is set to 2. Every time the state changes, javascript automatically calls a function specified by the onreadystatechange attribute. So, before calling a remote site, you should setup a new function:

xmlHttp.onreadystatechange=function()
{
  alert('state changed to '+xmlHttp.readyState);
}

This is how asynchronous requests are handled. Once you send a request, you access the response only through the onreadystatechange function. Meanwhile, your client page can be doing other things. If you are waiting for a response from the server, you should check whether the readyState is 4, corresponding to the request being completed. The server's response is returned as part of the XMLHttpRequest' responseText attribute.

xmlHttp.onreadystatechange=function()
{
  if(xmlHttp.readyState==4)
  {
    .... do some cool stuff ...
  }
}

For example, if you have following html file, server.html:

hello world

This server page just prints the hello world message.

Here is an AJAX implementation that gets the message from the server and prints it.

<html>
<body>
<script>
  var xmlHttp;
  xmlHttp=new XMLHttpRequest();

  xmlHttp.open("GET","server.html",true);

  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
    {
      var pElement=document.getElementById("msg");
      pElement.innerHTML=xmlHttp.responseText;
    }
  }

  xmlHttp.send(null);
</script>
<p id="msg"></p>
</body>
</html>

Sending Parameters

The parameters are sent either in the url (to, for example, a PHP page) or through the send function. Consider following PHP code that takes two parameters, multiplies them and return the result.

multiply.php

<? echo $_GET["x"]*$_GET["y"]; ?>

We can then use AJAX to get the multiplication of two numbers:

multiply-ajax.php

<html>
<body>
<script>
function multiply ()
{
  var xmlHttp;
  xmlHttp=new XMLHttpRequest();
  var x,y;
  x=document.getElementById("input_x").value;
  y=document.getElementById("input_y").value;
  xmlHttp.open("GET","multiply.php?x="+x+"&y="+y,true);

  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
    {
      var pElement=document.getElementById("msg");
      pElement.innerHTML=xmlHttp.responseText;
    }
  }
  xmlHttp.send(null);
}
</script>
x:<input id="input_x" type="text"/ ><br>
y:<input id="input_y" type="text"/>  
<a href="javascript:multiply();">Multiply</a>
<br>
------------------------</br>
Result: 
<p id="msg"></p>
</body>
</html>

Note that the x and y values are sent as part of the url as GET parameters. You can also send them as part of the send function, provided that your receiving page uses POST parameters.

multiply-post.php

<? echo $_POST["x"]*$_POST["y"]; ?>

multiply-ajax-post.php

<html>
<body>
<script>
function multiply()
{
  var xmlHttp;
  xmlHttp=new XMLHttpRequest();
  var x,y;
  x=document.getElementById("input_x").value;
  y=document.getElementById("input_y").value;
  var req="x="+x+"&y="+y;

  xmlHttp.open("POST","multiply-post.php",true);

  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
    {
      var pElement=document.getElementById("msg");
      pElement.innerHTML=xmlHttp.responseText;
    }
  }

  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", req.length);
  xmlHttp.setRequestHeader("Connection", "close");
  xmlHttp.send(req);
}
</script>
x:<input id="input_x" type="text"/ ><br>
y:<input id="input_y" type="text"/>  
<a href="javascript:multiply();">Multiply</a>
<br>
------------------------</br>
Result: 
<p id="msg"></p>
</body>
</html>

jQuery

jQuery is a fairly lightweight javascript library that has a number of particularly useful features. Even thought it's only been around for a few years now, it has gained a lot of momentum in the web development community. jQuery provides a simple interface to easily modify CSS attributes on all the elements in the HTML document, has simplified AJAX integration, and is accompanied by a number of handy user interface related APIs. You can get a good overview of jQuery in the jQuery Tutorials, and there is a short summary on Wikipedia. Of course, there are plenty of other tutorials a google search away.

To use jQuery in your javascript, you need to include the jQuery javascript library, which is just another JavaScript file. Google hosts jQuery for free, and it is recommended that you use Google's hosted jQuery for your projects (here is a blog post that gives some of the main reasons). Add the following line inside the <head> tag of your web page (adjust the version in the middle):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js" type="text/javascript"></script>

To get the link to the latest hosted jQuery, see the Google Hosted Libraries Developer's Guide.

You can also link to the jQuery library directly on other websites as mentioned in the above tutorials. The trade-off is that having a local copy will load faster, but then requires you to manage the library files your self (e.g., downloading new versions).

A few code snippets are given below, but the best way to learn about all the features of jQuery is to head to the jQuery website and look through the tutorials, references, and examples there.

The $ symbol is used to denote jQuery functionality. You can use it to call jQuery functions, access HTML document elements in order to read or write values, or modify style information via CSS for a range of document elements. For example, here is some code that sets up a function to be called whenever the user clicks on a link:

 $("a").click( function(event)
 {
   event.preventDefault();
   $(this).hide("slow");
 } );

The above code leverages many useful javascript and jQuery features. $("a") is the jQuery way of selecting all HTML a elements. That is, in this case, all elements in the HTML document that are <a> tags. The click function is invoked for all such a elements in the document. The argument to the click function is another function that is to be called when the selected elements are clicked by the user. The event argument to this user-defined function is a default argument sent to functions which handle user actions like clicking a mouse button. In this example, the code calls another function, preventDefault() on the event passed to stop the standard action on that event. Here that means stopping the web browser from following the link that the user clicked on. Finally, the $(this) variable is the jQuery way of accessing the current encapsulating object, as in Java. This example calls the jQuery hide function on the object to make the object (again, in this case, this is referring to the <a> tag that the user clicked) disappear from the browser. The script also passes an argument to the hide function to make the link disappear slowly as described in the API documentation.

jQuery also comes with some easy to use widgets for building better user interfaces. One of the handiest is the dialog widget that pops-up an in-browser dialog window. To use the dialog functions, you need to include a few more javascript libraries in your HTML header block like so:

 <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css"
 
type="text/css" rel="Stylesheet" /> <!-- We need the style sheet linked
 above or the dialogs/other parts of jquery-ui won't display correctly!-->

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script><!-- The main library. 
Note: must be listed before the jquery-ui library -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script><!-- jquery-UI 
hosted on Google's Ajax CDN-->
<!-- Note: you can download the javascript file from the link

provided on the google doc, or simply provide its URL

in the src attribute (microsoft and google also host the jQuery

library-->
 <script type="text/javascript">
   // your code goes here
 </script>

You can then use the $().dialog() function to make dialog boxes. The dialog function can take many arguments to customize its behavior and add standard elements like buttons; see the documentation for details. The content of the dialog box is typically placed in a div container and then that container is hidden when the document loads. You can put any elements in the div and they will be displayed as normal in the dialog box. Here is a full example:

 <html>
 <head>
  <style>
    #mydialog { display:none }
  </style>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css"
   type="text/css" rel="Stylesheet" /> 
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>
  <script type="text/javascript">
    function showdialog()
    {
      $("#mydialog").dialog();
    }
  </script>
</head>
<body>
  <input type="button" value="Show Dialog" onclick=showdialog() />
  <div id="mydialog" title="Howdy">Look at me!</div>
</body>
</html>

To understand the page, start at the bottom. There is a div element with a title and some string content. It also has a unique id (the ids can be anything you want) which is used to identify this particular element in the rest of the document. This div's id is mydialog. Above that is a button input. The only thing special about it is the onclick attribute which specifies a javascript function to call when the button is clicked by a user. In this case, the function is showdialog() which is a user defined javascript function contained in the document header. All the function does is access the document element with id mydialog (the #identifier is the jQuery way of accessing an individual element based on the assigned id in the element attribute list), and build a dialog box from it. Here, the dialog box will have the title Howdy from the title attribute in the mydialog element, and have a text string Look at me!. Finally, at the top of the document is the style section, which is a normal HTML/CSS section describing appearance of parts of the document. There is only one entry, again describing the document element with id mydialog. One style attribute is set, namely the display attribute is set to none to indicate that the element should not be displayed. Otherwise, the mydialog div would be displayed like any other part of the document rather than being used solely for our dialog box.

Here is another example of using jQuery to do simple animations by moving an image across the browser window:

<html>                                                                  
<head>                                                                  
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>          
<script type="text/javascript">                                         
  // these are for storing target locations
  var targetLeft=0;
  var targetTop=0;
  function moveTarget()
  {
    targetLeft+=10; //increase target location
    targetTop+=10; 
    $("#target").css("top",targetTop); //move target to (top,left)
    $("#target").css("left",targetLeft); 
    if(targetLeft<200) 
    { //stop if we reached left=200
      window.setTimeout("moveTarget()",200); //set the next timer
    }
  }
  $(document).ready( function() 
  { //at the beginning create a clock timeout
    window.setTimeout("moveTarget()",200); //call this function in 200 ms.
  });
</script>                                                               
</head>                                                                 
<body>                                                                  
<!-- this is my target-->                                        
<img id="target"  src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/180px-Smiley.svg.png" style="position:relative"/>
</body>                                                                 
</html>

Other Resources

There are a number of other w3schools tutorials and references that you may find useful, including PHP (note the PHP and AJAX section), DOM, AJAX, and CSS. Many other resources exist around the web, and you should feel free to incorporate any existing libraries or other javascript or AJAX-related tools. For example, the Google AJAX APIs.