Intermediate

How to access a database

The inherent JavaScript security restrictions prevent us from accessing files or other resources (outside of web accessible content) directly. This means we cannot access a database directly. There is a way around this though, and that is utilizing Ajax.

Via Ajax we can pass a request to a database with a server side resource, get some results back, and then update our page with those results. The results can be whatever we'd like - full tables, report data, or just what background image the user likes.

There are a number of considerations before undertaking this task.

How to show/hide page elements when an Ajax request starts or stops

Our users may get confused if they initiate an Ajax driven process but have no indication that something is happening. They may even think things are broken and abandon or abuse the application trying to fix it (clicking the link again and again.... ).

We can avoid this problem by simply showing a "loading" indicator of some sort. Some applications show the text "Loading...", while others use an animated image. Either way we can provide these visual indicators by hiding or showing content on our page.

How to load new content into an existing page element the easy way

Imagine you have a DIV on your page, and when a user clicks a link we want to replace the contents of that DIV with the HTML stored in a different file on our server. The easiest way to accomplish this is with the .load() method.


$("#mylink").click( function () {
$("#mydiv").load("page2.htm");
return false;
});

Here we have set up an event handler. But it's the second line that really does what we're after. It gets a reference to our DIV, then says to load the contents of "page2.htm" into that DIV. That's it. All nice and easy.

How to handle multiple references from a single selector

A selector may result in more than one element being referenced. For instance doing $("div") would result in a reference to ALL DIVs on the page being found. If we wanted to set the text on all the DIVs to a common value we might do something like this:

$("div").text("this is a div");