Javascript examples using the DOM

The xmlHTTP object

This uses the xmlHTTP object to get data from a server but without refreshing the page. Usually to get data from the server in response to a form or other user input we need to submit the form which reloads the entire page. This is very useful when we need to update part of a page with fresh data but don't want the current view to alter or page to reload.

Another great advantage is that we can carry out server side processing using PHP or any other language and return this data back to the page using this method. There seems to be a lot of talk about this right now and possibly some over use since the results can be pretty cool, but be aware that if you rely on this and your users have javascript turned off then your cool page will fail completely.

Some of the better known sites that use the xmlhttp object are Gmail which gives the site a very 'snappy' feel since the whole page does not need to be reloaded when clicking on links, Google Suggest which returns possible searches as you type based on the most likely results and Google Maps which allows you to 'drag' the map and load new maps in the background. I have also used this method on my contact page so that an email can be sent without navigating away from the contact page to the usual 'Thanks for contacting us' page which is otherwise quite useless. If you have javascript turned off then you can still email me as the form will then be submitted as normal.

Note that although it is called xmlhttp you can return any data you like, in my example I return a simple number, but you could equally return xml, maybe something like below in my example.

<?xml version='1.0' standalone='yes'?>
     <convert>
         <temp>69.8</temp>
     </convert>

Of course if you decide to send xml data from your script make sure you also sent the correct Content-type of text/xml, this is done with PHP like this:

 header('Content-Type: text/xml');

Also remember to use xmlhttp.responseXML instead of xmlhttp.responseText when getting the data. I decided not to return xml data as then I would have to parse the returned xml using javascript which was an unnecessary overhead in this simple case.

In this example the temperature and conversion required are sent via POST to the page 'add' on this server. The output from this script is then sent back to the page and the value displayed in the last field. The PHP script is very simple, it just takes the POST variables and uses them to convert from one temperature scale to another returning the resulting conversion. This code tests for window.XMLHttpRequest ( used by Mozilla, Safari, Opera ) and if this doesn't work then uses the Microsoft version of new ActiveXObject("Microsoft.XMLHTTP"), if both fail the function returns false. This created object is then set to the xmlhttp variable.

var xmlhttp=false;
if (window.XMLHttpRequest)
     {
     xmlhttp = new XMLHttpRequest()
     }
else if(window.ActiveXObject)
     {
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
     }
else
    return false;

Change the value of the result box label depending on whether we are converting to Fahrenheit or Celcius.

if(document.getElementById("f").checked)
    {
    document.getElementById("resulttext").replaceChild (document.createTextNode("Temp in C"),document.getElementById("resulttext").childNodes[0])
    }
else
    {
    document.getElementById("resulttext").replaceChild (document.createTextNode("Temp in F"),document.getElementById("resulttext").childNodes[0])
    }

Get the values of the text boxes and checkbox and send these values in a querystring to the page add using the GET method.

xmlhttp.open("GET", "test/add?temp=" + document.getElementById("temp").value + "&scale=" + document.getElementById("c").checked,true);

Here we wait until the data is recieved. We set up a function to be called when the state of the xmlhttp object changes, when readystate==4 then we show the data using xmlhttp.responseText ( or xmlhttp.responseXML if you are getting XML data from the server ).

xmlhttp.onreadystatechange=function()
     {
     if (xmlhttp.readyState==4)
       {
       document.getElementById("result").value=xmlhttp.responseText
       document.close()
       }
      }
 xmlhttp.send(null)
}





Regular Expression tester

This uses javascript to test a regular expression. If you enter the expression to match against in the 'RegEx match' field and the test string in the 'Text to compare' field. Click 'Compare' and either true or false will appear in the 'Is match?' field.

function test()
{
var strtest=document.getElementById("input").value;
var Exp=document.getElementById("strExp").value;
var myreg=new RegExp(Exp);
var ans=myreg.test(strtest);
document.getElementById("output").value=ans;
}




Traversing DOM nodes

This code asigns all the <DIV> elements to the variable tags using document.getElementsByTagName("div"). Next it loops through all the elements of this array until it finds an element with an id of 'pagebody', which is the main page content div on this page. Next it loops through all the childNodes of this div looking for all the h2 tags, then changes the background color to #228800 or #fff and text colour #fff or #000 depending on how many times the button has been pressed. Note that I also test for Internet Explorer using if(document.all) since it seems that IE requires uppercase tag names whereas Mozilla uses lowercase, as I would might have expected.

Press to toggle the background colour of all <H2> tags.

var toggle=0;
function highlight()
{
var div="div";
var h2="h2";

if (document.all)
    {
    div="DIV";
    h2="H2";
    }

var col;
(toggle%2==0)?col="#228800":col="#fff";
(toggle%2==0)?textcol="#fff":textcol="#000";
toggle++;
var tags=document.getElementsByTagName("div");
for(var x=0;x<tags.length;x++)
        {
        if(tags[x].id=="pagebody")
            {
            var newtags=tags[x].childNodes;
            for(var z=0;z<tags[x].childNodes.length;z++)
                    {
                    if(newtags[z].nodeName==h2)
                    		{
                        newtags[z].style.backgroundColor=col;
                        newtags[z].style.color=textcol;
                        }
                    }
            }
        }
}