Later Today: ASP.NET Tutorial 2: Introduction to C#

AJAX Tutorial 0: Core AJAX Concepts

Prerequisites: Some familiarity with HTML forms.

This article introduces basic JavaScript concepts, and builds on those concepts to explain how AJAX is used and, more importantly, why. This is not an in-depth look at JavaScript, nor is it intended to be. As with all tutorials on this site, you should already be familiar with X/HTML and CSS, and have a general idea of what JavaScript is and how it’s used. Some of those things will be briefly covered – but for more in-depth information, I recommend perusing the DOM and JavaScript articles at w3schools.com.

> Introduction to the DOM

Explains what a DOM is, how it works, and why it’s important.

Before discussing anything JavaScript-related, it’s absolutely vital that you understand the concept of a DOM (Document Object Model).

If you understand X/HTML (and if you’re reading this, you should), then you’re already half-way there. Every time you load a web page, your web browser takes all the pieces of HTML code (source code) and assembles them into a rigid structure, sort of like a file system. This structure is then used to calculate, process, and render all the content that you see. In particular, your pays special attention to the hierarchy of elements on the page (ie. which elements are inside which other elements). This "file system" is called the DOM, or Document Object Model.

For example, the following is some basic HTML source code, before it is compiled into a DOM.

HTML Source-Code:
<html>
   <head>
      <title>My Webpage</title>
   </head>
   <body>
      <p>This is a paragraph</p>
      <p>This is also a paragraph!</p>
   </body>
</html>

This source code is then assembled into the following DOM structure…

HTML DOM Structure:
  • html
    • head
      • title
    • body
      • p
      • p

In addition to basic structure, each element in the DOM has a number of properties associated with it. These properties dictate things like text-content, color, size, attributes, etc… and the browser uses all of them to determine how to display the page to you, the user. Where does it get these properties from? All over the place. Some of them are hard-coded into the browser (for instance, the browser knows how <p> tags behave by default), while others are created by any CSS, attributes, or styles you may have added.

So why does any of this matter? Because JavaScript allows you to change just about anything in the DOM, right from the user’s browser. More on this in the next section.

> Introduction to JavaScript

Briefly explains JavaScript and it’s uses

In the bad old days, once the server sent the source code for a web page to the browser – that was it. The page was rendered and there was nothing else you could do with it (unless the user did something that caused the page to be reloaded – in which case the source code being sent back to the browser might be different).

What makes JavaScript so useful is that it allows the DOM to be manipulated even after it’s been loaded and rendered. This let’s you do things like change text, add or remove HTML, or change CSS styling right before the user’s very eyes (and without the user needing to get new source code from the server).

The problem with plain-jane JavaScript is that it’s very basic and very limited. To do something more complex than change a bit of styling information would require extraordinary amounts of code. Furthermore, JavaScript’s ability to select elements in the DOM was limited to either elements with specific id attributes ( ie. document.getElementById('MyUniqueID') ), or making wholesale selections of elements by name (ie. document.getElementsByName('body') ).

The good news is that we now have the jQuery framework to simplify these types of tasks by a hundred-fold, while simultaneously allowing us to perform more complex DOM manipulation with an infinitesimal fraction of the coding.

> Introduction to jQuery

This section introduces the jQuery framework

jQuery is a widely-used Javascript framework created with the intention of making DOM manipulation and traversal (the act of finding DOM elements based on specific criteria) faster and more powerful than ever before.

For example, the following code is how you would change an element’s style in old-fashioned Javascript:

(JavaScript) Select element by ID and change styles
var eMyElement = document.getElementById('MyUniqueID');
eMyElement.style.color = 'red';
eMyElement.style.fontWeight = 'bold;

And this code does the same thing using jQuery (and without styles having to be translated from CSS to Javascript):

(jQuery) Select element by ID and change styles
$('#MyUniqueID').css({color:'red',font-weight:'bold'});

You may have also noticed that jQuery uses common CSS selectors for selecting elements. This is one of jQuery’s most powerful features – you can select any number of elements using simple CSS selectors (including CSS3 and dozens of additional custom selectors).

jQuery is not, however, a replacement for JavaScript. It is a framework – a standard collection of JavaScript code that you would otherwise need to write yourself to achieve the same results. So if you though you could completely escape JavaScript by using jQuery, then sorry – that’s just not the case.

To use jQuery in your own projects, you can either download the .js file and host it yourself OR you can simply link to the Google-hosted version (the url can be found here).

jQuery will be discussed in more detail in a later article. If you’d like to learn more immediately, the jQuery website has a lot of excellent tutorial resources. I recommend starting with this one.

Note: NetBeans and Visual Studio 2010 both support full JavaScript and jQuery code-hinting/intellisense. While working on JavaScript code, simply hit Ctrl+Space to see options.

> Introduction to AJAX

This article introduces AJAX, what it’s used for, and how it works.

What the heck is AJAX?

AJAX is an acronym for Asynchronous Javascript and XML. In plain English, AJAX is a way of using JavaScript that finally allows the server and the webpage to communicate with one another in real time. This means that web pages can send chunks of data to a server (just like submitting a web form) and the server can send chunks of data back (usually as XML), then JavaScript is used to update the DOM. The reason this is so damn cool is that allows you to create web pages that look and behave exactly like programs that you run on your own computer (and without the need for unreliable 3rd-party browser add-ons like Adobe Flash).

Many popular online services are extremely AJAX-heavy: Facebook, Bing, GMail, Google Maps, Google Docs, and My Yahoo!, just to name a few.

Note: The “asynchronous” part of AJAX means that any number of requests & responses can be juggled at the same time. The code does not have to wait for one to finish before another one can start. This is important since passing data back and forth takes time, even if it is usually so small that humans don’t notice.

How does AJAX work?

In order for AJAX to work, you have to be running a server-side technology like ASP.NET or PHP. Here’s why…

The JavaScript sends data to a URL the same way a typical HTML web form sends data (via a standard GET or POST request). The major difference being that JavaScript can send the data without the need to leave the page (it simply does it behind-the-scenes). The server then processes that data the same way it would any other form submission, and sends an XML file back instead of a web page. JavaScript then grabs what it needs from the XML file (still completely behind the scenes) and uses that data to manipulate the DOM.

Because all of that happens behind-the-scenes, from the user’s perspective, they interacted directly with the webpage. The fact that processing took place on the server – or that the webpage was communicating with a server in any way – is completely hidden from the user. In effect, this gives a webpage the ability to behave just like a normal computer program (albeit with the extra advantage that the data stored on the server and is available from anywhere).

How is AJAX used?

In the not-so-distant past, doing something was AJAX was an exercise in frustration, requiring dozens of lines of code for a single request. It was also buggy as all-get-out, especially on webkit-based browsers (Safari & Chrome). Fortunately, jQuery makes AJAX so easy it’s ridiculous. Instead of the dealing with monolithic amounts of code for what amounts to a simple task, jQuery comes with $.get(), $.post(), and $.ajax() functions that do all the heavy lifting for you. This is what a simple AJAX post request looks like using jQuery:

jQuery AJAX Example (Sending a GET Request):
jQuery.get(
   "http://example.com/get-responder",
   { key1:"Value1", key2:"Value2"},
   function(response){ /*Do stuff*/ }
   "xml"
);

The above code sends a GET request to the URL http://example.com/get-responder (just like submitting a form with method=”get”), and sends the data contained in the next line as key value pairs. As a query string, this request would look like this: http://example.com/get-responder?key1=Value1&key2=Value2

The third line is an anonymous function that handles the callback (that’s the XML file that server sent back when AJAX sent the GET request). We’ve named the response “response“, and can select elements with jQuery the same way we’d select them from HTML (more on this in later tutorials). This is also the place you would generally put any code you want to use to make changes to the current webpage/DOM.

Finally, the last line tells jQuery to expect an XML response (as opposed to HTML, JSON, or another type of data). This isn’t vital, but it does help minimize the chance that jQuery will be confused with the response.

Hopefully you understand a little bit more about how exactly all the pieces fit together to make AJAX work. The next article in this series will introduce JavaScript basics.

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...