Login

Save Password - Forgot Pass?
Not a member?
Become a DC
member now!



Dynamic data using the DOM and Remote Scripting
Written 02/20/2002 by Thomas Brattli. Last updated 02/21/2002. Print-friendly version. Back to regular version.


How it works

As most of you probably know the DOM allows us to dynamically create almost any element that can be on a page, so we use it to create a SCRIPT tag that we set a src to. When setting the src of a script tag then adding it to the page the DOM browsers will try to load the script file that we specify.

First I'll make a reusable function that we can use to load the new content into the page with:


function loadContent(file){
  var head = document.getElementsByTagName('head').item(0)
  var scriptTag = document.getElementById('loadScript');
  if(scriptTag) head.removeChild(scriptTag);
  script = document.createElement('script');
  script.src = file;
	script.type = 'text/javascript';
	script.id = 'loadScript';
	head.appendChild(script)
}

Let's go line by line;
var head = document.getElementsByTagName('head').item(0)
This just makes a short reference to the head element. Used later in the function.
var scriptTag = document.getElementById('loadScript');
This line tries to get the script tag called loadScript. The first time this function is called this will return null because the tag does not exists.
if(scriptTag) head.removeChild(scriptTag);
If the tag exists we remove it because we don't want all the old tags to stay in the page. In explorer you don't really have to do this, you can just set a src to the existing script element but that doesn't seem to work in Mozilla.
script = document.createElement('script');
This creates a script tag.
script.src = file;
This line sets the src of the script tag to the file that you specify when you call the function.
script.type = 'text/javascript';
We set the type of the script tag to text/javascript
script.id = 'loadScript';
Here we set the ID to loadScript so we can reach it with the second line in the code the next time this function is called.
head.appendChild(script)
Then we add the script tag to the page with the appendChild function. It's added to the head of the page.

So if you call the function like this:
loadContent('myfile.js')
it's more or less the same as adding a script tag with regular code like this:
<>


Note that the file you load in a script tag like this HAVE to be a JS file. You cannot load another HTML file or whatever like this. It has to valid script inside the file.

Ok, now we know how it works, but what can we do with it?

There are tons of things we can do with this technique, let's start of with a simple example

Simple example

I had a hard time finding a very simple example for this one so I'll make a totally useless one just so you can see that it works.

Example 1

This doesn't really start to get really powerfull before you start using it together with some server-side stuff though. Let's say you had a page with stock quotes, you could set the script to reload and get the latest stock quotes every 2 minutes and the user would never have to reload the actual page, the only thing updated is the quotes.

Anyway, let's move on to the menu script

Menu script

Let's say you have a menu similar to the foldoutMenu from this site with 200 menu items. This is a modified and a little simplified version where the script only loads the top items as HTML (making the older browsers use the main items only), and loads the other elements with the loadContent function only if and when they are needed.

I'll start by showing you the menu (the first menu and the second sub and subsub menu opens new items)

Example2

This is a simple version of the menu basically to give you the idea (i know, i know, the code is a mess), note that I don't mean that you should use this script, it's only intended to help you understand the basics of this technique. Though by all means feel free to reuse the code if you like.

We make the top items manually. That way they will be shown and works in all browsers. The submenus only works in dom browsers. Right now I will not write more about how this works, you're on your own. The source-code has a lot of comments that should help you understand it (it can be downloaded at the end of the tutorial).

I'll give you one more example to give you the idea of how I use this script.

ASP Menu script

This part of this tutorial shows an ASP example and you should know some ASP to understand this.

As mentioned before this doesn't really become useful until you start doing some backend stuff. Let's say I have a database with 500 products divided in 10 categories and stored in a database (again simplified example).

Database tblCategories:
dbID - autonumber
Catname - Txt
Database tblProducts:
dbID - autonumber
Productname - Txt
Productinfo - Txt
category - Number - related to DBID in table1

You would probably want to add some more info in there, like price and whatever, but you get the idea.

Then we have some data like this in tblCategories:
dbID Catname
1 Software
2 Hardware


And in tblProducts:
dbID Productname Productinfo category
1 Homesite 5 The best code editor around 1
2 44 inch flat screen Use the computer as your home-cinema screen 1


Now we are ready to start displaying the data. The first page displays the categories as topMenus: (note that I code ASP in JScript - so should you!)

//Pointer to the database
database="Provider=Microsoft.Jet.OLEDB.4.0;"
  +"Data Source="+Server.MapPath("example.mdb")+";"

//opening db
q="Select * from tblCategories"
rs=Server.CreateObject("ADODB.Recordset")
rs.open(q,database)

//looping records
while(!rs.EOF){
  name=rs("catname").value
  id=rs("dbid").value
  Response.write('<
>' +'<><>'+name+'<>' +'<
>\n\n') rs.moveNext() } rs.close() rs=null
The second page "products.asp" is that page that will be loaded with the js loading. If you're thinking "Hey, I thought you said that it had to be js file!!" your right, so we have to get the server to return the content as a javascript file. We do that with this little line:
Response.ContentType="text/js"
So the entire products.asp looks like this:
@LANGUAGE=JAVASCRIPT

//Getting the ASP page to return a js file
Response.ContentType="text/js"

//Getting the id
catid = Request.queryString("id")

//Pointer to the database
database="Provider=Microsoft.Jet.OLEDB.4.0;"
+"Data Source=" + Server.MapPath("example.mdb") + ";"

//opening db
q="Select * from tblProducts where category = "+catid
rs=Server.CreateObject("ADODB.Recordset")

rs.open(q,database)

//looping database records
while(!rs.EOF){
  txt=rs("ProductName").value + " " + rs("ProductInfo").value
  id=rs("dbid").value
  Response.write('addElements("'+txt+'","","show_product_details.asp?id='+id+'")\n')
  rs.moveNext()
}
rs.close()
rs=null

Response.write("loaded()")

Again, this was a simple example, and the only thing it does is get the info from the db and display in the menu from the last example. I have not included any product display page or any error checking. But I am sure that if you get the point of this example you'll see that a similar approuch could be used to load entire tables of data in all kind of cool ways.

Download

You can download all the examples from this tutorial here (with the database and ASP files).

More examples on gow to use this technique will come!

Good luck!

Copyright ©2000-2002 DHTMLCentral.com, Bratta Communications. All rights reserved.