back to contents

Web Dev: Javascript/AJAX Magic

the history of javascript

I told you in the HTML/CSS guide that you didn't need to worry about HTML5, and you shouldn't. Javascript is a part of the HTML5 revolution. You may not need to worry about it, but you should know a few things.

Javascript used to be shunned by everyone. It used to be a clunky, untrustworthy language, that would break in almost every browser.

But now, thanks to a lot of cool people, Javascript is useful again! In fact, Javascript (usually referenced as the buzzword AJAX) has made a giant comeback.

It's fun to note that technically speaking, javascript itself hasn't changed at all. The only things that have changed are how people think about it and how browsers support it. Developers have faith in the language.

yet another programming language

Like PHP, Javascript is a programming language. However, like HTML, it's on the client side.

As I said about PHP, it's kinda dangerous to have things on the client side, but the lines are blurring. You can integrate the two worlds rather nicely, which is why I wanted you to learn PHP first. Know the two worlds, client-side and server-side, before you begin to mix them.

Javascript has variables, functions, control structures, etc, just like PHP. But it lives in the browser and you can view the source. It can't go as deep as PHP can, but it can get close.

learning Javascript

Most people probably would've taught you Javascript before teaching you PHP, but not me. I don't think we really live in that world anymore.

If HTML is the chassis, and PHP is the engine, then Javascript is all the fancy bells and whistles that make the car work and feel pretty cool. That's what Javascript has turned into by our perception.

Javascript has made a huge comeback mostly because of two things: reliability between browsers and popular libraries or frameworks.

Just like HTML, Javascript is now very reliable between browsers. What will work in Chrome will also work in Firefox and IE... 99% of the time. It'll also probably work on mobile phones, too.

And like in PHP, Javascript now has many user-created libraries which make it far more extensible and easy-to-use.

Javascript vs AJAX

As I mentioned, AJAX is kind of a buzzword. AJAX literally means Asynchronous Javascript And XML, even though that's rarely how it's properly used.

Really AJAX is just a fancy thing people came up with to tell people, it separated the new from the old. It's a smart marketing move: rename something to remove it's old negative connotations.

I mean, AJAX definitely is a part of Javascript. But it's like referring to cake by just the colorful frosting.

So really that's all there is to say. When anyone says they're some kind of AJAX guru, they're really saying they know some pieces of Javascript.

where does javascript go?

In any HTML page, in the head section, you put Javascript between some script tags, like so:

<html>
<head>
<title>page title!</title>
<script type="text/javascript">

// javascript goes here!

</script>
</head>
<body>

</body>
</html>

That's it! However, like CSS, you can put it in a separate file if you want, and load it like so:

<html>
<head>
<title>page title!</title>
<script type="text/javascript" src="some_file.js"></script>
</head>
<body>

</body>
</html>

In that scenario, some_file.js would have to hold your javascript code. Put it in the same folder as your HTML file.

variables, functions, etc

You should know all about these concepts now if you followed the PHP guide well. Here's how they look in Javascript.

Instead of having a dollar sign before the variable name, in javascript you use the keyword var before the variable name, like so:

var some_var = 20;

Note that there's the same equals sign meaning assignment, the same number data type, the same semicolon at the end of the line.

The only difference is that instead of $some_var, it's var some_var. Technically you don't even need the var there, but it's useful to.

Javascript is, technically, much looser than PHP. Any collection of characters without quotes around it is either a variable or a keyword...

Functions look the same:

function add(a, b) {
  var c = a + b;
  return c;
}

Again, no dollar signs for variables. Just var, if we use it at all. We could've written it without that one var keyword.

Instead of NULL, javascript has undefined, and it means what it sounds like. If we were to ask javascript about some random variable we hadn't used yet, it would say the variable is undefined.

javascript arrays and objects

Like PHP, there are simple arrays in javascript, and they look like this:

var fruits = [ 'apple', 'orange' ];

However... there aren't really any associative arrays. Instead, there are straight-up raw objects. And they work pretty much the same way as associative arrays. Like so:

var favorites = { color: 'red', food: 'pizza' };

Instead of square brackets [ ] for a simple array, objects get curly braces { }.

In PHP, the key-value pairs are denoted by the => assignment operator. In javascript, they're denoted by simply a colon between the key name and the value.

And we can access these name-value pairs through the period or dot accessor:

favorites.color

That would return the string red. So that's how they work in Javascript. We set color to be a property of the favorites object with the string value 'red'.

an objective approach

The biggest difference between PHP and Javascript is the programming paradigm used to write it.

Javascript is far more object-oriented than PHP is. Most everything in Javascript is an object which has things that can be done upon it.

In PHP, most of the programming focuses around using PHP's functions. In Javascript, most of the programming focuses on using a given object's methods.

For example, here's how we count the length of an array in PHP versus how it's done in Javascript. First, PHP:

<?php
$an_array = array('hello', 'goodbye', 'cya');
$array_length = count($an_array);
?>

The count function will give us the length of the array! Here's the same thing in Javascript:

var an_array = [ 'hello', 'goodbye', 'cya' ];
var array_length = an_array.length;

What's the difference? It's subtle, but it's systemic. In PHP, we made the array, and then to get the amount of elements in the array, we call the built-in function count().

In Javascript, we make the array, and then we look at what its length is. The array object has a built-in property called length that always has the array's length. It's not one that's built into Javascript, it's built into the object. Understand the difference?

The way I usually think about it is that PHP takes instructions, one line at a time. Javascript takes instructions, one object at a time. I could have written the same thing as before this way:

var array_length = [ 'hello', 'goodbye', 'cya' ].length;

The [ ] is an array object and length is its property called by using the period to access it.

It's hard to really describe until you see it a lot... because technically you could make a similar shortcut in PHP:

$array_length = count(array('hello', 'goodbye', 'cya'));

But you notice how it's presented: the javascript way puts the properties and functions in the objects, the PHP way performs functions onto the objects.

It's subtle, but very important.

so writing javascript

... is a lot like writing PHP. Except when you read the reference documentation for javascript, you need to think about what object you're using.

In PHP you can read all the String functions, but in Javascript you have to read all the String properties and methods.

method is another word for function, except usually you hear method when talking about object-oriented programming.

Expressions work the same way as PHP. If and else work the same way. Operators, too. Functions, as I've said. Loops work the same way, with for and while loops.

libraries

The biggest difference is that with contemporary javascript, the majority of developers rely on libraries to do the heavy lifting.

Some popular ones include jQuery and Prototype. You may have heard of them before; nearly everybody uses them. Even Google.

You download and include the libraries and then build your code on top of it. This is a good thing and a bad thing...

On the one hand, you don't have to worry about doing a lot of things yourself; the libraries give you shortcuts! And they're written to work across browsers so you don't have to worry about it.

On the other hand, you are now dependent upon those libraries, ones that you didn't write yourself and may be well over your head. So they add a level of complexity on top of your code that you hopefully never realize.

Libraries are worth the risk, though, especially the big ones. They're very well documented and if you have problems, there are a lot of people to ask for help. I've used Prototype and jQuery extensively myself.

the DOM, aka The Matrix. haha

One thing that modern browsers have accepted and become reliable on is what's known as the DOM. It's kinda like The Matrix, in that it defines the whole page and everything in it, really.

DOM stands for the Document Object Model of a webpage's HTML and CSS. This is all a part of the standard way of writing code I was talking about in the HTML/CSS guide.

When you write a web page in HTML correctly, all the tags inside the HTML form a tree or hierarchy of information. There are parents, children, classes, IDs, etc. Remember that? If you don't, check this out for a refresher:

<html>
<body>
<div id="onlydiv">
<p class="redtext">hello!</p>
</div>
</body>
</html>

So here we have the body tag and its child is the div tag. The child of that div tag is the p tag. So the p tag's parent is the div tag. The p tag also has a class name associated with it, and the div tag has an ID associated with it. These are all a part of the page's DOM. It's just a hierarchy of information.

The DOM is simply Javascript's understanding of that hierarchy so that you can use each piece of your HTML as an object! You could use Javascript to select the div with its ID and do something to it if you wanted.

Again, javascript is big on objects and wants everything to be an object, including your HTML elements.

so let's do something

Before we even load up a library to use, let's do something to the above HTML code with plain old Javascript's built in methods.

Add in a head section and a script tag like I showed you before. You can save the file as jtest.html if you want and open it in a browser while we edit it.

Inside the script tag, let's put this javascript code:

function changeText() {
  var thediv = document.getElementById('onlydiv');
  thediv.innerHTML = '<p>replacement text!</p>';
}

So we've made a function. If you load the page, it doesn't do anything yet, because nothing is calling the function. But let's first look at what this function will do.

First of all, it's called changeText, and it takes no arguments, as we can see because of the empty parentheses.

Inside of it, it creates a variable called thediv, which is assigned something which looks strange. Let's break it down.

First, it gets the document object, which represents the whole page. document is a DOM object.

The document object has many methods, one of them being getElementById(), which takes one argument: an ID as a string.

So we are asking the document object to get an HTML element that has the ID 'onlydiv'. And we know that there's only one thing on the page that has that ID.

Okay, awesome. With that element assigned to the thediv variable, we can now tell that object to change its innerHTML property. This is exactly what it sounds like.

Changing the innerHTML property on any DOM object will change the HTML within it. In this case, we want to replace what's inside the onlydiv element with a new string!

Do you understand what I mean? Read it again and follow along what it's saying. Don't be intimidated by all the periods and uppercase/lowercase and whatnot. Just try to read it like a sentence.

events drive the interface

Another thing Javascript loves almost as much as objects are events. Javascript, in most usage, is an event-driven language. A user clicks something, and Javascript runs a function to do something. We'll do that now.

So in your HTML code, under the first div, add another div! And add this button inside that new div:

<input type="button" value="do it" />

Ok so if you reload your page, you should see the hello! text and a button underneath it. Right now the button doesn't do anything, so let's add an event for javascript to watch for:

<input type="button" value="do it" onclick="changeText()" />

That new button has one new attribute: the onclick event listener. Javascript will now listen for someone to click the button, and when someone does, it'll perform the changeText() function.

Notice that we can't just put a call to the changeText() function inside the script tags... that's because javascript can only use the DOM after the whole page has loaded. You can't call the function up there at the end of the script tag because it'll execute the function before any of the body section has loaded.

So it goes like this:

  1. Your browser requests a page
  2. Your browser reads the HEAD section of the HTML
  3. Your browser reads the BODY section of the HTML and renders it
  4. Then the browser will be ready to do anything with the DOM

If you try to do javascript calls which affect the DOM in that second step, it'll just get confused because none of the BODY has loaded yet.

In today's world these four steps happen so fast (it typically takes mere hundredths of a second) that you'd expect it to have no problem. For the most part, steps 2 and 3 happen almost simultaneously. But you can't depend upon it, it's not safe to.

That's why we need to push out the actual execution of functions to depend on events. The body itself being done loading is an event!

<body onload="changeText()">

You could do that if you wanted. That'll make sure that as soon as the body is done loading it'll perform the changeText() function, and not before.

mixing the worlds, again

The above example of putting the onclick or onload attribute inside the HTML element is a lot like when we put the CSS inside an individual HTML element's style attribute. Remember how I told you that doing so wasn't the best way of doing things?

It's not exactly how a lot of people think you should do things with Javascript, either. I won't tell you that any which way is right or wrong, I'll just tell you how most people do things, and why it's effective. But there are a hundred ways to do this.

jQuery gained a lot of popularity because it helps separate the javascript from the HTML in the same way people already separate CSS from HTML.

jQuery, your first library

Well, first of all, jQuery is just a library. A library builds upon the language by using the language. It is not its own language, it just helps you out by doing work for you. Libraries give you shortcuts.

There are many, many, many libraries for Javascript. jQuery is a popular one. Specifically, it's useful for selecting things in the DOM and listening for events. It's also very useful for AJAX calls, but we'll get into that later.

Just for reference, the jQuery documentation is here. It's pretty good, but it could be better.

To use jQuery, we need to load it. So head on over to jQuery dot com and hit the download button on the right. It'll download a .js file, put it wherever you've been keeping your test files for these guides.

To load it in an HTML page, do the same you'd do to load any file, as I showed you before:

<html>
<head>
<title>page title!</title>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
</head>
<body>

</body>
</html>

(At the time of this writing that's the filename for jQuery, but replace it with whatever you downloaded. The file needs to be in the same directory as this HTML file.)

Ok so now we have the jquery script library loaded. For us to do things with it, let's make another script tag to put our functions and stuff in.

Inside that new script tag we'll put our code, using the jquery library.

jQuery uses a special function, the $ function, to do a lot of its work. (Not to be confused with PHP's use of the dollar sign.)

It's a great function. It takes one argument, which can either be a DOM object or a string. If you use a string, it'll act like a CSS selector. Wait a second - it'll act as a what!? Read this:

var loldiv = $('div#somediv');

So we have a variable called loldiv and it is assigned the value returned by the $() function. We gave that function a string that looks a lot like a CSS selector for a div with the ID 'somediv'. So the loldiv variable is now that element.

That's pretty magical... using in Javascript something we learned in CSS. And it makes sense, too! Why not re-use something that works so well already?

var loldiv = $(document);

That'll get you the whole document. Notice how there are no quotation marks - document is a DOM object already, it's not a CSS selector.

So actually, we'll use the document DOM object to make this work and separate the Javascript from the HTML like I talked about.

$(document).ready( function() {
  // do whatever you want here
});

Ok, what does this do? It might be confusing with all the parentheses and the curly braces, but just break it down a piece at a time. It waits until the document object is ready, and then it does whatever is inside the function.

We have the $(document) object and we use the ready() method on it -- that'll add a listener for when the document is ready. We pass that method a function. Inside the function will be whatever we want to happen when the document is ready.

We then have to close the function and then close the ready method. Hence the }) at the end. And don't forget to finish it with a semicolon! (Because technically you could've written all of that on one line, we break it up just for readability.)

Yes, that function inside the ready() method doesn't have a name -- but in Javascript, it doesn't need one. Javascript has what's known as anonymous functions, for one-time uses like this. You can't call that function directly since it has no name - but Javascript will know to use it because we wrote it into the ready() method.

Here, we could have written it this way:

function doWhenReady() {
  // do whatever you want here
}

$(document).ready(doWhenReady);

Notice there's no () after the function call inside the ready() method -- that's because it wants an object... and a function, technically, is an object. Everything is. At least in Javascript. It's going to call that function whenever it's ready.

For the most part, this is better than the onload body attribute! Mostly because it's designed to wait until exactly when you can do anything on the page.

So let's replicate that onclick attribute, but with jQuery. So we start with this:

$(document).ready( function() {
  // do whatever you want here
});

And we now add this:

$(document).ready( function() {
  $('#thebutton').click( function() {
    // do whatever!
  });
});

So what does this do? It waits until the document is ready, and then it finds an element on the page with the thebutton ID, and it says when clicked, do this function. Inside that function we could do whatever we want, and it would happen when we click on the element with that ID.

That's the basics of jQuery... there are a lot of methods attached to jQuery objects, most especially AJAX ones, which I'll explain in a minute.

Errors in Javascript

Yes, it gets to be kind of a mess of parentheses and curly braces. You just have to make sure you follow along closely. Make sure every opening brace or parenthetical is eventually closed, or else you'll get errors. And they're not obvious like in PHP.

And what's horrible about Javascript is that it's terrible at reporting errors... it usually just fails and doesn't tell you at all. This is why, in the Web Dev Intro, I said you should get comfy with tools like Firebug. They can do that error-reporting better than the browser does.

So download it! Get Firefox, if you don't have it already, and then install the Firebug extension. I'll wait.

You should now have a little bug icon in the lower-right of your Firefox window. Click on it. The first thing it'll show you is the source code of the page in a fancy layout. That's pretty cool, too.

It'll also show you - see the tabs along the top - the page's CSS, its javascript, etc. The important part here is the Console. Here is where any Javascript errors will show up!

So it's useful to keep the Console open when you think there's a problem. Javascript will report errors in bright red, so you can't miss em.

what AJAX really is

So I told you before that AJAX is just javascript, and that's true. But AJAX commonly refers to a particular set of functions within javascript.

When you use AJAX, you do so primarily to load content from other pages without leaving the current page. Or you can even send content to other pages without having to go to them. This is a big deal.

However, I should tell you right now, that I don't think you should actually use the AJAX way of doing things until after you learn the non-AJAX way. I'll teach you both, but don't go running to AJAX just because it might be flashier. It's much more open to security problems and it's harder to debug.

Usually things would flow like this:

  1. Go to a page on a website
  2. Click on a button or link on the website
  3. You go to another page or whatever, following the link or form you clicked on

That's all well and good. It's how the internet was designed: going from one page to another, distinctly. But if you notice, while using services like Google Mail, you never seem to leave the same page. It just loads your email in the current page! That's AJAX.

An AJAX-driven page might work like this:

  1. Go to a page on a website
  2. Click on a button or a link on the website
  3. Javascript calls for that page in the background
  4. Javascript takes the result and parses it how you want it to, like replacing the contents of a div
  5. (Your location on the internet hasn't changed! You're still on the same page.)

AJAX's primary job is to replace existing content on the page with content loaded from other pages. Kinda simplistic, but mostly true.

an AJAX example

Here's a rough example. First of all, we have this page:

<p>Haha, this is some new text!</p>

Save that. Don't put any html tags around it, literally save that one line as an HTML file. Call it piece.html

Ok, now on to the real file. Call this one container.html

<html>
<head>
<title>simple AJAX example</title>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
  $('#someButton').click( function() {
    $.ajax({
      url: 'piece.html',
      success: function(data) {
        $('#contentBox').html(data);
      }
    });
  });
});
</script>
</head>
<body>
<div>
<input type="button" value="load external content" id="someButton" />
</div>
<div id="contentBox">
<p>loaded content will go here</p>
</div>
</body>
</html>

That's one hell of a loaded example, but it should work, if you have all three files (the two .html files and the jquery file) in one directory.

First, let's examine the container page. In the body, we see two divs: One with a button on it, the other just has some text in it. No big deal. What's important is that the button and the second div both have IDs. That means we can use them easily in Javascript.

The javascript is where the action is. It basically says this:

So..... what does all this add up to? When you click on the button, the browser loads piece.html, and replaces the contents of the contentBox div with whatever is inside piece.html

Like magic.

How powerful is this? Extremely. It kinda turns the whole linking part of the internet on its head if you only need one page to hold everything, and other pages just to act as satellites for it, holding content to replace content.

That was a very, very elementary example. When you combine this with PHP and databases, shit gets real crazy.

what to use javascript for

It's useful for driving actions. It's useful for making otherwise dull events on a website seem fancy. I won't delve much into how to do that...

The developer's job is rarely to carve that out. That's why this review of javascript has kind of been lax on examples and more conceptual in nature.

I wanted you to know what javascript could do, but not really how you can immediately use it.

I also wanted you to realize how much Javascript is like PHP, and any other programming language. It's all the same basic concepts, with different vocabulary.

It's like spoken languages... yes, there are different syntaxes, different dictionaries, but it's all just communication of ideas. In the case of programming, we're finding various ways to communicate with a computer.

carry on my wayward son

Learn about databases next. At the end of the web dev series, I'll provide you a grand huge awesome example of how this all ties together. Trust me.