Javascript FAQ
Javascript FAQ
Javascript FAQ
Javascript FAQ
Javascript FAQ
Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ
Javascript FAQ Javascript FAQ
Javascript FAQ
Go Back  Xtreme Visual Basic Talk > > > Javascript FAQ


Closed Thread
 
Thread Tools Display Modes
  #1  
Old 05-21-2003, 07:07 AM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Talking Javascript FAQ


For easier access:
1) Fully customizeable new window.
2) Regular Expressions and form validation.
3) Cookies and Javascript.
4) Creating your own objects.
5) OOP & Javascript.
6) Event Handling.
7) Manipulating Listboxes.
8) Dynamically changing contents of containers.
9) Basic String Handling.
10) Debugging those HTML objects at runtime
11) Using Ajax for Asynchronous Web Communications

Since Javascript is my main choice (and I'm sure others) for when it comes to writing client-side scripts for web pages (VB Script only works on Internet Explorer), I decided to show a series of posts that may clear up some FAQs some members may have. Up first is my version of a fully customizeable new window:
Code:
<head>
<script type="text/javascript"> 
// Why I'm not using - language="JavaScript" - go here

var newWin = null; //in case you want to manipulate the new window elsewhere

function openWindow(fileToOpen,winName,w,h) { 
// fileToOpen = file the new window will try to load 
// winName = the name you want to give the window 
// w = width of window 
// h = height of window 
// remember that arguments start will index of 0 NOT 1:
// arguments[4] = optional startup coordinate for the left side of the window 
// arguments[5] = optional startup coordinate for the top of the window 
// arguments[6] = extra items you want to enable/disable in the window 
// example calls (tested on IE6 & NS7): 
//   openWindow("test.html",'popup',400,400,"","","status=yes" )
//   openWindow("test.html",null,400,400)

  var argLength = openWindow.arguments.length;  //retrieve the actual amount of arguments sent into the function
  var leftDef = 200;var topDef = 200; //default startup coordinates

  if (argLength < 4) {alert("All four parameters must be passed to the openWindow function!" );}
  else {
    var settings="height=" + h + ",width=" + w;
    if (argLength > 4) { //optional parameters were passed in
      //isNaN for some reason accepts an empty string as a number
      if (isNaN(openWindow.arguments[4]) || openWindow.arguments[4] == "" ) {settings += ",left=" + leftDef;}
      else {settings += ",left=" + openWindow.arguments[4];}   
      if (argLength > 5) { 
        if (isNaN(openWindow.arguments[5]) || openWindow.arguments[5] == "" ) {settings += ",top=" + topDef;}
        else {settings += ",top=" + openWindow.arguments[5];} 
        if (argLength > 6) {settings += "," + openWindow.arguments[6];} 
      } 
    } 
    newWin = window.open(fileToOpen,winName,settings); 
    newWin.focus(); //set focus to the window
  }
} 
</script>
</head>
Notice I put it in the head portion of the html doc. You could also throw this into a Javascript include file for multiple html files that need it.

More info on window.open (what is available to that browser):
- For Internet Explorer, go here
- For Netscape, go here

A nice tutorial of manipulating windows: http://webreference.com/js/tutorial1/index.html
- includes centering, opening one to full-screen, determining if closed/open, move to a location, resizing, writing to, referencing parent window from child, dialog boxes, and other misc info.
- Direct link for comparison of extra features for both browsers:
http://webreference.com/js/tutorial1/features.html

Quick reference on window methods/properties/events:
http://www.devguru.com/Technologies/...ef/window.html

What is next? Regular Expressions and Form Validation.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb

Last edited by wayneph; 11-03-2005 at 08:59 PM. Reason: Updated Navigation Links
  #2  
Old 05-21-2003, 10:42 AM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Regular Expressions and form validation...

Regular expressions are great for form validation because they can be quite powerful for analyzing if the user's inputted data is acceptable. Lets say you want to validate your fields before going to the server. Side Note: One should also do a data check on the server-side for tricky users who can bypass the client-side check.

A simple example situation might be like the following:
Code:
<html><head>
<script type="text/javascript"> 
function validateFields(form) {
  var field = form.ssn; // Social Security field
  var expression = /^\d{3}-\d{2}-\d{4}$/; //format of ###-##-#### (no spaces on either end is allowed)
  if (!expression.test(field.value)) { // if data isn't valid
     alert("Please follow the format of ###-##-#### when entering your SSN.");
     field.focus(); //set focus to the field
     field.select(); //select the contents so user can type over what is currently in the field
     return false; //don't go to the link in the action field
  }
  return true;
}
</script>
</head>
<body>
<form method="post" action="somelink.asp" onsubmit="return validateFields(this)">
Your Social Security Number:<br /><input type="text" name="ssn" size="12" /><br />
<input type="submit" value="Send Data" />
</form>
</body></html>
There can be multiple expressions that accomplish the same validation, so you need to work out what is best for you.
My expression above can also be written as:
/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/;
/^[0-9]{3}-\d{2}-[0-9]{4}$/;
other possibilities...

A nice tutorial on regular expressions:
http://www.webreference.com/js/column5/index.html

Nice tool to validate regular expressions:
http://builder.cnet.com/webbuilding/...8/toolrei.html

Edit: Above is no longer a valid link, try this one instead.


Quick reference on the properties/methods available:
http://www.devguru.com/Technologies/...ef/regexp.html

What is next? Creating and Retrieving Cookies.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb

Last edited by alp0001; 08-11-2004 at 09:47 AM. Reason: Added Link
  #3  
Old 05-21-2003, 05:03 PM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Cookies and Javascript

A cookie is basically a small file with some data in it, located in a standard cookies folder (depending on which browser you use). Javascript cookies are great for all kinds of scenarios. One example is where a developer wants to allow a client's computer to automatically login to one of its password-protected pages after that user has logged in correctly the first time.

Important info about cookies:
- The user needs to have Javascript turned on (if manipulating with cookies on the client-side).
- The user needs to have cookies enabled in order for them to work. One way of detecting this would be setting a cookie and then try to retrieve it.
* The following limits may change with the constant change in technology:
- Netscape - look for "Specifications for the Client".
- Microsoft - look for "Browser Cookie restrictions".

There is no need to repeat any code for setting/deleting/retrieving a cookie since it is posted well around the internet. One good example is from here:
http://www.webreference.com/js/column8/functions.html
along with a tutorial about cookies:
http://www.webreference.com/js/column8/index.html
or here:
http://hotwired.lycos.com/webmonkey/...x1a_page7.html
or here:
http://htmlgoodies.earthweb.com/beyond/cookie.html - or - http://htmlgoodies.earthweb.com/tutors/cookie.html

For the example scenario I gave: On the first successful login of the user, the appropriate Javascript can then set a cookie on the user's machine storing user id/password information. When the user comes back to the login page at a later time, the appropriate Javascript can then try to retrieve the cookie that was set before. If there was none set, then the login page is presented. If there is a cookie set, then the login page can get bypassed. The psuedocode would go something like the following:

(Before the login document is displayed)
- Try to retrieve login and password cookie values
- If none available, keep loading the current page.
- Else redirect user to appropriate page.
(After user logins correctly)
- Set appropriate cookies for the user id/password.

What is next? Creating your own Objects.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb
  #4  
Old 05-22-2003, 09:25 PM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Creating your own objects

It took a while before I stumbled onto this one when I was new to Javascript. Javascript provides different ways for creating your own objects. Objects are great for combining multiple values (and different data-types) into a single unit. A sample scenario would be working with a car object:
Code:
<html><head>
<script type="text/javascript"> 
function SeatsObj(amount,type) {
   this.seatNum = amount; //property created for seats object
   this.seatType = type; //propery created for seats object
}
function moveCar(amount) {   
   this.speed = this.speed + amount;
   if (this.speed == 0){this.tires.state = "Stopped";}
   else {this.tires.state = "Moving";}
}
function showValues(obj) {
   var parts;
   for (parts in obj) {
     document.write(parts + " has stored: " + obj[parts] + "<br>");
   }
}
//
// create a car's defaults
//
var car = new Object(); //create a car object

car.name = "Galant"; //give it a name (a property)
car.speed = 0; //mph
car.tires = new Object(); //create a tires object onto the car object
car.tires.brand = "Firestone";
car.tires.count = 4;
car.tires.state = "Stopped";
car.seats = new SeatsObj(4,"leather"); //create a seats object onto the car object another way 
car.move = moveCar; //create a method for car (notice no parameters are needed for this initial setup call)
car.specs = {height: 72, width: 70, color: "red"}; //create a specs object onto the car object another way
</script>
</head>
<body>
<script type="text/javascript"> 
//show the contents before and after when one of the car's methods is called
document.write(car.speed + " " + car.tires.state + " (move method invoked) ");
car.move(20);
document.write(car.speed + " " + car.tires.state + "<br>");

//show what is in the object car
document.write("<br>car:<br>")
showValues(car);
document.write("<br>car.tires:<br>")
showValues(car.tires);
document.write("<br>car.seats:<br>")
showValues(car.seats);
document.write("<br>car.specs:<br>")
showValues(car.specs);
     
</script>
</body></html>
A tutorial about creating your own objects can be found here:
http://www.javascriptkit.com/javatutors/object.shtml

Microsoft has some pages about this also:
http://msdn.microsoft.com/library/de...ml/objects.asp
(other related links on the left frame)

What is next? Taking Objects further...Object-Oriented Programming.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb
  #5  
Old 06-05-2003, 03:34 PM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default OOP & Javascript

The last post was just to show that there are different ways of creating an object. This post will show the preferred method (using the same scenario from the previous post) and show some OOP using various techniques. OOP questions may not come up as much since it is a little advanced, but I thought this would be a good extender off of the previous post.
Code:
<html><head>
<script language="Javascript1.5">
//The following will be bypassed in IE, since it isn't at 1.5 yet.  It does work in NS 7 though!

function Car2() {
   //How to create a class constant that can't be changed (like Math.PI):
   this._gas = "Regular";
   this.gas getter = function () {return this._gas;}
   this.gas setter = function (n) {return;}

}
</script>

<script type="text/javascript"> 
//tested in NS 7 and IE 6

function moveCar(amount, tireObj) {   
   this.speed = this.speed + amount;
   if (this.speed == 0){tireObj.state = "Stopped";}
   else {tireObj.state = "Moving";}
}
function showValues(obj) {
   var parts;
   for (parts in obj) {
     document.write(parts + " has stored: " + obj[parts] + "<br>");
   }
}
function deepCopy(curObj) {
   var name;
   for (name in curObj) {
      this[name] = curObj[name];
   }
}
function Tires() {
   this.brand = "Firestone";
   this.count = 4;
   this.state = "Stopped";
}
function Seats(amount, type) {
   this.seatNum = amount;
   this.seatType = type;
}
function Specs() {
   this.height = 72;
   this.width = 70;
   this.color = "red";
}
//create a car constructor (sets defaults to the newly created object)
function Car() {
   // add properties
   this.name = "Galant";
   this.speed = 0; //mph
   // add objects
   this.tires1 = new Tires();
   this.seats1 = new Seats(4,"leather");
   this.specs1 = new Specs();
   // add a method
   this.move = moveCar;
}
//Show inheritance is possible (Jaguar is a particular car);
function Jaguar() {
   this.name = "Jaguar"; //override the property in the object Car
}
Jaguar.prototype = new Car;

// Set up another property that is available to all car objects (in case someone forgot to add it in the constructor).
// (One can also create methods using prototype as well).
Car.prototype.insurance_agent = "Allstate";

</script>
</head><body>
<script language="Javascript1.5">
var car1 = new Car2();
var oldinfo = car1.gas;
car1.gas = "Premium"; //try to change it...will do nothing
document.write("<b>Show a true class constant at work</b>: " + oldinfo + " : " + car1.gas + "<br><br>");
</script>

<script type="text/javascript">
//good way to copy an object
var car2 = new Car();
car2.name = "Ford";
var car3 = new deepCopy(car2);
car3.name = "Lincoln";
document.write("<b>Deep copy of an object</b>: <br>");
document.write("Car2: <br>");
showValues(car2);
document.write("Car3: <br>");
showValues(car3);

// Bad way to copy an object.
// Copying objects like the following will cause unexpected results
var car4 = car3;
car4.name = "Prowler";
document.write("<br><b>Shallow Copy of an object</b>: <br>");
document.write("Car3: <br>");
showValues(car3);
document.write("Car4: <br>");
showValues(car4);

var car5 = new Jaguar();
document.write("<br><b>Show sample inheritance of an object</b>: <br>");
document.write("Car5: <br>");
showValues(car5);
</script>
</body></html>
A tutorial about Javascript OOP can be found at the following locations:
http://www.webreference.com/js/column79/index.html (very good)
http://www.webreference.com/js/column80/index.html (very good)
or
http://www.javascriptkit.com/javatutors/proto1.shtml
http://www.javascriptkit.com/javatutors/oopjs2.shtml

What is next? Event Handling.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb
  #6  
Old 06-18-2003, 04:36 PM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Event Handeling

There are all kinds of events that can be trapped/manipulated/used in many ways. They can range from a mouse click on a specific button to a mouse click (or key press) anywhere within the webpage. An example follows:
Code:
<html><head>
<script type="text/javascript">
// tested with IE6,NS7

var prevKey = 0;

function keyHandler(evt) {
// There will be some keys that will need to be modified to the programmer's satisfaction.
// (One example is the results when the period is pressed)
// Hint: it involves looking for a keycode of 190

   var cursorKey, key, shift = 16;
   var divContainer = document.getElementById("div1");

   if (evt) { // Netscape
      cursorKey = evt.which;
   }
   else { // non-Netscape
      cursorKey = window.event.keyCode;
   }

//the following is very useful if you don't know what code a certain key has in a specific browser
//   alert(cursorKey);

   key = String.fromCharCode(cursorKey); //change the keycode to a letter
   if (prevKey != shift){key = key.toLowerCase();} //the key is normally uppercase (which we normally don't need)
   if (shift != cursorKey) { //don't need to put the shift key in the message.
      divContainer.innerHTML = divContainer.innerHTML + key;
   }
   prevKey = cursorKey;
}    
if (document.layers) { //Netscape needs this
   document.captureEvents(Event.KEYDOWN);
}
document.onkeydown = keyHandler;
</script>
</head>
<body>
<div id="div1">Type some more text to add here!<br /></div><br />
<form name="frm1">
<input type="button" name="btn1" value="Click here" onclick="alert('The button was pressed');window.focus();">
</form>
<span onmouseover="alert('The mouse is over the message')">Mouse over me!</span>
</body></html>
How Netscape handles events:
http://www.webreference.com/js/column9/
How Internet Explorer handles events:
http://www.webreference.com/js/column10/
Cross-Browser Event handlers:
http://www.webreference.com/js/column11/
Another location (in case you didn't like the previous ones):
http://www.wdvl.com/Authoring/JavaSc...nts/index.html

Quick event references:
http://www.juicystudio.com/tutorial/...pt/events.html
http://www.devguru.com/Technologies/...nthandler.html

Sample Disabling of right-mouse button and related opinions:
http://www.xtremevbtalk.com/show...threadid=62063

Sample game that uses events (tetris):
http://www.dynamicdrive.com/dynamicindex12/tetris2.htm

What is next? Manipulating List Boxes.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb
  #7  
Old 06-27-2003, 10:00 AM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Manipulating Listboxes

There are many things one can do with listboxes. I set up a small example to show most of what can be done with them:

Code:
<html><body>
<form name="frm1">
<select name="items">
<option value="1">First Item
<option value="2">Second Item
<option value="3">Third Item
</select>
</form>
<script type="text/javascript">
//tested in IE6 and NS7
var itms = document.frm1.items; //set a reference to the items list

itms.selectedIndex = 1; //set the second item as the selected value
document.write (itms.value); //will show a 2 since that is the value of the 2nd item
alert("Now lets make the listbox bigger to allow more elements to be seen...");
itms.size = 3;
alert("Now lets temporarily disable the listbox...");
itms.disabled = true;
alert("Now we will change the first item in the listbox...");
itms.options[0].text = "Changed Item";
itms.options[0].value = "0";
alert("Now lets remove the last item");
itms.length = 2; //can also be done with itms.options[2] = null;
alert("See if the second item is still selected: " + itms[1].selected);
alert("Now lets allow for multiple selections after enabling it again (hold the control key down)...");
itms.disabled = false;
itms.multiple = true;
</script>
</body></html>

Rezner's example in populating dynamic listboxes (blank listboxes must be present):
http://www.xtremevbtalk.com/t55739.html

Tutorial on creating a lookup list:
http://www.webreference.com/js/column15/index.html

Navigation Example (has a builder as well):
http://www.echoecho.com/jsdropdown.htm

Quick reference to all properties/methods/events available:
http://www.devguru.com/Technologies/...ef/select.html

What is next? Dynamically changing contents of containers.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb
  #8  
Old 07-13-2003, 09:13 PM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Dynamically changing contents of containers.

Ever need to change the content of something? Maybe it was an explanation box for when a user moved his/her mouse over certain links. Maybe it was for changing the page all together. Whatever the reason, this FAQ example is probably for you:

Code:
<html><head>
<script type="text/javascript">
//will only work on IE6
var count = 0;
function changeIt() {
   var divContainer = document.getElementById("div1");
   if (count == 0) {
      alert("Current text: " + divContainer.innerText + " will now be changed...");
      divContainer.innerHTML = "The DIV text is now different.";
      frm1.btn1.value = "Click here to change the Div into a <p> tag once";
      count++;
   }
   else if (count == 1) {
      divContainer.outerHTML = "<p id='p1'>I'm now stored in the paragraph tag!</p>"
      var pContainer = document.getElementById("p1");
      alert("Using the id of the paragrah: " + pContainer.innerText);
      count++;
   }
}
</script>
</head><body>
<div id="div1"><b>This text should be BOLD!</b></div>
<form name="frm1">
<input type="button" name="btn1" value="Click here to change the Div text once" onclick="changeIt();">
</form></body></html>
(Example 2)
Code:
<html><head>
<script type="text/javascript">
//will work on IE6 & NS7
var count = 0;
function changeIt() {
   var divContainer = document.getElementById("div1");
   if (count == 0) {
      alert("Current text: " + divContainer.firstChild.childNodes[0].nodeValue  + " will now be changed...");
      divContainer.innerHTML = "The DIV text is now different.";
      document.frm1.btn1.value = "Click here to change the Div into a <p> tag once";
      count++;
   }
   else if (count == 1) {
      var p = document.createElement("p");
      p.setAttribute("id","p1");
      var pText = document.createTextNode("I'm now stored in the paragraph tag!");
      p.appendChild(pText);
      var bodyContainer = document.getElementsByTagName("Body").item(0);
      bodyContainer.replaceChild(p,divContainer)
      var pContainer = document.getElementById("p1");
      alert("Using the id of the paragrah: " + p1.childNodes[0].nodeValue);
      count++;
   }
}
</script>
</head><body>
<div id="div1"><b>This text should be BOLD!</b></div>
<form name="frm1">
<input type="button" name="btn1" value="Click here to change the Div text once" onclick="changeIt();">
</form></body></html>
*** I could have gotten rid of the innerHTML for the second example and added the appropriate JS. However, doing it this way is easier (since it works in NS and IE anyway).

Nice IE only tutorial (also covers insertAdjacentText and insertAdjacentHTML which I have left out):
http://www.webreference.com/dhtml/column5/index.html
Small example that works with IE & NS
http://www.webreference.com/js/column73/3.html

Explain what you are using in sample 2! Ok, go at the following links for tutorials on the DOM:
http://www.webreference.com/js/column40/index.html
... (keep adding onto the column number)
http://www.webreference.com/js/column44/index.html
... (more examples on later columns...keep adding onto the column number)

What is next? Basic String Handling.

Any suggestions on what should be included, give me a PM.
__________________
Avatar by the very talented member: lebb

Last edited by alp0001; 12-19-2003 at 08:45 AM.
  #9  
Old 12-19-2003, 08:36 AM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Basic String Handling

It is just a matter of time before one needs to use strings in Javascript. Since this is primarily a VB website, I will compare some VB functions used to the equivalent Javascript functions one should use. I'm not going to give all the Javascript String functions, only the ones that members will probably use more often.

Before the attached comparison, it is important to note that Strings can be created in different ways:
Code:
var testString = new String("This is a new string"); // String object
var testString = 'This is a new string'; // string literal
var testString = "This is a new string"; //string literal
Using a particular method depends on what you need:
Code:
var testString1 = "1 + 1" // string literal
var testString2 = new String("1 + 1") // String object
eval(testString1) // returns the number 2
eval(testString2) // returns the string "1 + 1"
Basically, Javascript will temporarily change the literal into a String object so you can use the String methods on it, but (as shown above) some unexpected results may come forth if not too cautious on what one uses.

Quick reference on all the String properties/methods available:
http://www.devguru.com/Technologies/...ef/string.html
http://www.w3schools.com/js/js_string.asp

What is next? Debugging those HTML objects at runtime.

Any suggestions on what should be included, give me a PM.
Attached Files
File Type: zip comparison.zip (1.8 KB, 8 views)
__________________
Avatar by the very talented member: lebb

Last edited by wayneph; 09-27-2005 at 09:53 PM. Reason: Added "What's Next"
  #10  
Old 09-27-2005, 07:52 PM
alp0001's Avatar
alp0001Javascript FAQ alp0001 is offline
Ultimate Contributor

Retired Moderator
* Expert *
 
Join Date: Jan 2002
Location: Lakemoor, IL
Posts: 2,826
Default Debugging those HTML objects at runtime.

Hello all,

This really isn't a FAQ when it comes to Javascript, but it may be a helpful debugging utility for you. Basically, you can dynamically ask the webpage to look at a current object's attributes/values or even change the object's attributes/values. As such, running this script on any browser of your choice will show what attributes your particular browser will allow for an object reference you typed in.

Here is a sample way of calling the script:
HTML Code:
<html><head><script type="text/javascript" src="alp_debug_obj.js"></script></head>
<body onload="alp_CreateDisplay();"></body></html>
Pretty simple..eh ?

Here is the JS file:
Code:
// Adam Petrie
// Created: 09/27/2005
// Revised: 02/15/2006  (to make it more user/browser friendly). 
// Revised: 10/05/2006 (slightly faster, more user/browser friendly, supports
//                      innerHTML and outerHTML values now, and a few comments added).
// Functionality:
// Show current values held by a particular object given through the user.
// Also, user can dynamically change attributes (like the background color).
// Tested the following browsers (on XP OS): IE 6.0, NS 8.1.2, Opera 9.2, Firefox 1.5.0.7
// Sample usage: onload="alp_CreateDisplay();"  - from the body HTML tag.

function alp_BtnGet_click(e) {
// Event to start the processing...
   alp_ResetDiv();
   window.status = "Working...";
   alp_ShowValues(document.getElementById("alp_txt1").value);
   window.status = "Results should be displayed."; 
   return true;
}
function alp_CreateDisplay() {
// Creates a debugging display on the bottom of the page.
  var bodyContainer = document.getElementsByTagName("Body").item(0);
  var alp_div_obj_txt, alp_new_obj;
  
  // create page separator
  alp_new_obj = document.createElement("hr");
  bodyContainer.appendChild(alp_new_obj);

  // create the directions
  alp_new_obj = document.createElement("div");
  alp_new_obj.setAttribute("id","alp_JS_info_2");
  alp_div_obj_txt = document.createTextNode("Type in Object: ");
  alp_new_obj.appendChild(alp_div_obj_txt);
  bodyContainer.appendChild(alp_new_obj);

  // create the text input field
  alp_new_obj = document.createElement("input");
  alp_new_obj.setAttribute("id","alp_txt1");
  alp_new_obj.setAttribute("type","text");
  alp_new_obj.setAttribute("size","40");
  alp_new_obj.setAttribute("value","document.body");
  bodyContainer.appendChild(alp_new_obj);

  //create 'Get Values' Button
  alp_new_obj = document.createElement("input");
  alp_new_obj.setAttribute("id","alp_btn1");
  alp_new_obj.setAttribute("type","button");
  alp_new_obj.setAttribute("value","Get Values");
  alp_new_obj.onclick=alp_BtnGet_click;
  bodyContainer.appendChild(alp_new_obj);

  //create 'Clear Results' Button
  alp_new_obj = document.createElement("input");
  alp_new_obj.setAttribute("id","alp_btn2");
  alp_new_obj.setAttribute("type","button");
  alp_new_obj.setAttribute("value","Clear Results");
  alp_new_obj.onclick=alp_ResetDiv;
  bodyContainer.appendChild(alp_new_obj);   
}
function alp_ResetDiv() {
// Clears the contents of the DIV displaying all the results.
   window.status = "";
   var alp_div_obj = document.getElementById("alp_JS_info_1");
   if (alp_div_obj != null) {
      alp_div_obj.innerHTML = "";
   }
}
function alp_ShowValues(inVal) {
// Will show all the attributes/objects for a object passed in by the user.
   var alp_doc_obj, bodyContainer, alp_div_obj_txt;
   var alp_div_obj = document.getElementById("alp_JS_info_1");
   var alp_txt_obj = document.getElementById("alp_txt1");
   var alp_pos = 0, alp_inner_pos = -1, alp_outer_pos = -1;
   var alp_obj_value_array=new Array();
  
   //Make sure the display DIV hasn't been created yet as this function can be called multiple times.
   if (alp_div_obj == null) { 
      //create the div to show the results
      alp_div_obj = document.createElement("div");
      alp_div_obj.setAttribute("id","alp_JS_info_1"); 
      alp_div_obj_txt = document.createTextNode("");
      alp_div_obj.appendChild(alp_div_obj_txt);
      bodyContainer = document.getElementsByTagName("Body").item(0);
      bodyContainer.appendChild(alp_div_obj);      
   }
   //Reference the 'object' (or change the attribute) the user typed in.
   try {
      alp_doc_obj = eval(inVal);
   } 
   catch(e){  
      alert("Try using a different object reference instead.");
      alp_txt_obj.focus();
      alp_txt_obj.select();
      return false;  //don't continue the rest of the statements...   
   }
   
   //Get all the attributes from the browser and then sort them
   for (alp_obj_value in alp_doc_obj) {
     alp_obj_value_array[alp_pos] = alp_obj_value;
     alp_pos++;
   }
   alp_obj_value_array.sort();
   
   //Display attributes and their values
   alp_div_obj.innerHTML = "Object passed in: <b>" + alp_txt_obj.value + "<\/b><br \/><br \/>";
   for (alp_pos=0; alp_pos < alp_obj_value_array.length; alp_pos++) {
   //Not showing innerHTML or outerHTML attributes yet as the actual controls will be created 
   // on the page and it could make for some interesting problems.
        if (alp_obj_value_array[alp_pos] == "outerHTML" ) {
        	alp_outer_pos = alp_pos;           
        }
        else if (alp_obj_value_array[alp_pos] == "innerHTML") {
        	alp_inner_pos = alp_pos;
        }
   //Show what the attribute/object is currently referencing.
        else {
           try {
              alp_div_obj.innerHTML += "<b>" + alp_obj_value_array[alp_pos] + "<\/b> has stored: " + 
alp_doc_obj[alp_obj_value_array[alp_pos]] + "<br \/>";
           } catch(e){ alp_div_obj.innerHTML += "<b>" + alp_obj_value_array[alp_pos] + "<\/b> gives an error!<br \/>";}
        }
   }
   /// Need to create BOTH textarea controls first (otherwise error). ////
   if (alp_inner_pos != -1) { 
     alp_div_obj.innerHTML += "<b>innerHTML<\/b> has stored:<br \/><textarea rows=10 cols=90 id=alp_JS_info_3><\/textarea><br \/>";
   }
   if (alp_outer_pos != -1) { 
   	 alp_div_obj.innerHTML += "<b>outerHTML<\/b> has stored:<br \/><textarea rows=10 cols=90 id=alp_JS_info_4><\/textarea>";
   }
   alp_div_obj.innerHTML += "<br \/>Total Shown: " + alp_obj_value_array.length;
///////////////////////////////////////////////////////////////////////
/// Now Populate the controls appropriately.///////////////////////////
   if (alp_inner_pos != -1) {    	 	
     alp_div_obj = document.getElementById("alp_JS_info_3");
   	 alp_div_obj.value = alp_doc_obj[alp_obj_value_array[alp_inner_pos]];   	
   }
   if (alp_outer_pos != -1) {   	
   	 alp_div_obj = document.getElementById("alp_JS_info_4");
   	 alp_div_obj.value = alp_doc_obj[alp_obj_value_array[alp_outer_pos]];   	
   }
///////////////////////////////////////////////////////////////////////    	
}
*Feel free to use it however you want. The attached zip has the same two files in this post. It also has other examples. The change_JS.html example will not work in Firefox/Netscape, so use either IE or Opera to see it work.

What's Next? Using Ajax for Asynchronous Web Communication

Any suggestions on what should be included, give me a PM.
Attached Files
File Type: zip JS_Debug.zip (3.8 KB, 6 views)
__________________
Avatar by the very talented member: lebb

Last edited by wayneph; 10-08-2006 at 08:42 AM.
  #11  
Old 11-03-2005, 04:43 PM
wayneph's Avatar
waynephJavascript FAQ wayneph is offline
Web Junkie

Retired Moderator
* Expert *
 
Join Date: Apr 2004
Location: D/FW, Texas, USA
Posts: 8,393
Default Ajax isn't just for cleaning anymore. (Asynchronous Web Communications)

Ajax is a new direction in web development that allows for Asynchronous communication in your web applications. Now you don't have to refresh an entire page or IFrame when you only have a couple small things that need to change. Basically it gives web developers the ability to have richer interfaces that run in the browser. I'm just beginning to play with this, but it looks like it will add a lot of power to existing and future web sites.

The tools used for Ajax aren't exactly new. Support started in IE 5, and has spread to Firefox 1.0 and Safari 1.2. The core object that makes this all possible is the XmlHTTPRequest object. While I'll only have a basic example here, you can see all of the XmlHTTPRequest object's properties and methods here. Basically it allows you to submit a request to the server behind the scenes and then use the response to change elements of the page that is currently being displayed. All of the changes are handled by JavaScript, CSS and the Document Object Model (DOM).

There are three steps needed to successfully update a web page.
  1. Create the Object.
  2. Send a Request
  3. Use the Results

1. Creating the Object. This is a fairly strait forward step, but a key is that the object needs to be global to the page, and not hidden in a function. Since the asynchronous response will be handled by a separate function the object needs to be outside of a specific functions scope. When creating the object basically you'll need to test to see if you're in IE, or another browser. I have a Function that creates the object and returns a Boolean stating if it was successful.
Code:
var xhr; //This is the object we'll be using.

function createXHRObject() { //called in the next step
  if (window.ActiveXObject) {
    //Microsoft uses an ActiveX Object
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
    return true;
  }
  else if (window.XMLHttpRequest) {
    //Firefox and Safari have it built into the Document Model
    xhr = new XMLHttpRequest();
    return true;
  }
  else {
    return false;
  }
}
2. Sending the Request – This is what gives Ajax all it's flexibility. Depending on what you're doing, this is where you can create your dynamic URL, POST data or XML document to send back to the server. In this example we're just going to create a URL and use the "GET" method. In reality you'd probably be passing parameters to a server side language like .NET, ASP, or PHP. Since I don't know what you have, I'm just using 3 static files.
Code:
//The city variable is just an ID matched to the name of the page on the web site
function getLocation(city) {
  //Only try to use the object if it's actually created
  if (createXHRObject()) {
    //The open method tells the object where it's going
    xhr.open("GET", city + ".html");
    //The onreadystatechange property tells the object what function to call when it returns.
    //displayLocation is written in the next step.
    xhr.onreadystatechange = displayLocation;
    //The send method actually starts the call.
    //If sending post data, or and XML Document, you'd pass it in here.
    xhr.send(null);
  }
  else {
    alert("Ajax not supported");
  }
}
3. Use the results - This is what is going to vary the most in different applications. Here I'm just taking the results, and sticking everything into a <div> tag that exists on the page. The attached file actually parses the text and reads some of the data out of the page for a customized display.
Code:
function displayLocation()
{
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      document.getElementById("content").innerHTML = xhr.responseText;
    }
  }
}
As this is a giant shift in the way web pages work, there are some things that you'll need to look at and test to make sure you are ready. The following Items may not work exactly as they have in the past since you're not always working with a full page. Printing may only print items on the initial load, The Back, Next and Refresh buttons won't pick up changes via XmlHTTP, you may have to do additional work to get a "static" link to your dynamic data. Depending on your scenario, these may be benefits or pitfalls to your application. Only testing will determine which.

I have done all my testing running this through a server environment. Attempting to run from the C:\ drive only gave problems. As soon as I changed to http://localhost or uploaded it to a server, the problems cleared up. This is one of the more common issues people have while testing these methods.

Obviously this can be used for a lot more than just pulling up a little bit of data. You can validate individual fields on forms before sending the entire form to the server, or you can get details about items from a summary page and your imagination is the limit. Depending on your needs, you can load a template as your main page, and run your entire site using Ajax. The possibilities are endless.

A very good book: Foundations of Ajax

Some other sites: AJAXMatters and AJAX Patterns

One list of sites already using these techniques: http://www.ajaxmatters.com/r/resources?id=2 (Google Maps and Netflix are two I use regularly.)

The attached file contains an example that will allow you to mouse over a few different cities, and have the page updated with that city's Current Time and their global coordinate. Have fun.

Any suggestions on what should be included, give me alp0001 a PM.
Attached Files
File Type: zip ajax.zip (1.9 KB, 26 views)
__________________
-- wayne, MSSM Retired
> SELECT * FROM users WHERE clue > 0
0 rows returned

Last edited by wayneph; 11-03-2005 at 08:54 PM.
Closed Thread


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
dynamic javascript? diver Web Programming 7 05-22-2003 01:05 AM
javascript within HTML....help trostycp Web Programming 3 11-10-2002 02:50 PM
ASP:Popup window? Use VBS instead of Javascript. idi0t Web Programming 4 10-12-2002 12:26 PM
webbrowser disable javascript AnAx Communications 0 05-09-2002 03:54 PM

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Javascript FAQ
Javascript FAQ
Javascript FAQ Javascript FAQ
Javascript FAQ
Javascript FAQ
Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ Javascript FAQ
Javascript FAQ
Javascript FAQ
 
Javascript FAQ
Javascript FAQ
 
-->