Browsing articles in "JavaScript/Ajax"
Nov 18, 2008

traversing the XML DOM

in one of my earlier posts about the i discussed how to bring in data via using the . i mentioned two ways of retrieving the information from an external file. the first was responseText and the other was responseXML. in this article i will demonstrate how to use the responseXML to retrieve information from an external xml file using the xml dom. (for this example lets assume you are using the xml example from the post, and that you have already returned the xml dom object and stored it in xmlDoc)

to get the information out of this file we will need to use getElementsByTagName. this will return an array containing all dom object that match the tag we reference:

var user = getElementsByTagName("user");

in the example we had 2 user elements. so the variable user now contains both those elements. now lets create a loop so we can cycle through all the elements a pull out whatever we need.

for (var i = 0; i < user.length; i++) {
}

now within the loop we need to add whatever code we want to retrieve the information we desire. lets say we want to grab the name and age tags. since these are childNodes of the user tag, we will add a second loop to cycle through all childNodes of the current user iteration.

	var child = user[i].childNodes;
	for (var j = 0; j < child.length; j++) {
	}

so now we are looping through every user element, and for each one we are then looping through all its childNodes. Now we can pull out the information withing the childNodes and display that information on the screen:

		document.write(child[j].firstChild.nodeValue);

the firstChild represents the text stored withing the element’s tags, however it doesn’t represent the value of the text, just the textNode itself. nodeValue represents the actual value of the textNode. so in plain english, that line of code is retrieving the child element, then getting the text node out of the element, retrieving the value of that text, and displaying it. if we put the whole code together it looks like this:

var user = getElementsByTagName("user");
for (var i = 0; i < user.length; i++) {
	var child = user[i].childNodes;
	for (var j = 0; j < child.length; j++) {
		document.write(child[j].firstChild.nodeValue);
	}
}

and will out put:

John Doe25Jane Smith28

with a little added formatting, or perhaps the use of some to create new elements, the text can be formatted and displayed in a slightly more appealing manor, but you get the point.

Oct 29, 2008

using the XMLHttpRequest

with all the emerging web applications out there, ajax has come overwhelmingly popular as a means to have active content on a page update without the need to re-load. one of the easiest way to achieve this is to use the XMLHttpRequest.

i have stated before that i am not an advocate of writing browser detection scripts since it makes more sense to check for the appropriate method when carrying out a task. in order to achieve this with the XMLHttpRequest is quite simple: write a function that attempts to create an XMLHttpRequest a number of ways and returns the results on success or an error on failure.

the function:

function new_request() {

	if (typeof XMLHttpRequest != "undefined") {
		return new XMLHttpRequest();
	} else if (typeof ActiveXObject != "undefined") {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		throw new Error("XMLHttpRequest not supported");
	}

}

simple enough right? now whenever you need to make an XMLHttpRequest a few lines of code will get the information you need

using the function:

var url = "/my_file"; // the path to the file you want to use
var request = new_request();
request.open("GET", url, true);
request.onreadystatechange = function() {
	if (request.readyState == 4) {
		// the code you want to run when the file/data is loaded
	}
}

XMLHttpRequest can return two forms of data: xml dom object and text. this means, depending on what you ask it to do withing the request.readyState == 4 statement, you will be given a certain type of data. if you are simply making a call to a text file that contains a paragraph and you want to display that paragraph you would use the following code:

var txt = request.responseText

while this can be usefull if you have many small txt files that make up the content of a page, i feel it is infinitely more powerful to store the same data in an xml file and just traverse the file to get the data you need from it. to do this you would use the following line instead:

var xmlDoc = request.responseXML

this would allow you to work with the xml dom to pull values out of the file as you need them. so the full code to bring the data in would be the following:

var url = "/my_file.xml"; // the path to the file you want to use
var request = new_request();
request.open("GET", url, true);
request.onreadystatechange = function() {
	if (request.readyState == 4) {
		// the file will be read in as an xml dom object
		var xmlDoc = request.responseXML;
	}
}

you can now traverse the xml dom object to get whatever data you need out of the file. i will be writing instructions on how to traverse the xml dom in another post so this is where i will end.

Oct 22, 2008

cross browser getElement function

in the ever changing world of browser warfare it seems as if the may never be a completely universal way of developing web applications. i’m constantly having to find ways to carry out a particular task that will yield the same results on all browsers. one such task is getElementById. until we can safely say that every web browser out there will perform the same task, or even recognize is, we need to determine what action we really need to take.

i am not an advocate of writing blatant browser detection scripts and then writing subsequent code based on what browser is detected. its poor coding, and it can get extremely too messy very quickly. instead i prefer to write specific functions that attempt to perform the task at hand a few different ways until the right way is determined. it makes the flow of the overall program much more logical.

the function

function getElement(target) {

	if( document.getElementById ) {
		object = document.getElementById(target);
	} else if( document.all ) {
		object = document.all[target];
	} else if( document.layers ) {
		object = document.layers[target];
	}
	return object;

}

how to call

var object = getElement("myId");

the function simply checks which method works, and returns the object. simple. so no matter what browser is being used, a simple call to getElement will return the correct getElementById results.

Oct 22, 2008

cross browser event handler

on my most recent project i needed to create event handlers to control actions taken when certain things were clicked on. in my case it was a multi-tiered navigation menu, but this has so many amazing applications like context (right-click) menu’s etc.

catch the event
first i placed javascript in the of document to capture the onmousedown event (onclick is not as cross browser friendly) and set it to perform a function i called eHandler rather than take the usual action.

<script>
<!--
if (window.addEventListener)
document.addEventListener('click',eHandler,false);
else if (window.attachEvent)
document.attachEvent('onclick',eHandler);
-->
</script>

the eHandler function
next i wrote the eHandler function to perform various tasks depending on what was clicked. this comes in handy if you want to have different task performed depending on what is clicked.

function eHandler() {

	// get the event
	if (!e) var e = window.event;

	// cross browser method to get the element that was clicked on
	if (e.target) elem = e.target;
	else if (e.srcElement) elem = e.srcElement;

	// get the element's id
	var elem_id = elem.getAttribute("id");

	// catch right clicks, rightclick is a boolean
	if (e.which) rightclick = (e.which == 3); // old netscape way
	else if (e.button) rightclick = (e.button == 2); // modern way

what we have so far
at this point the function now knows what element was clicked on, that element’s id, and whether the user right clicked or not. from here we can add various check and carry out various task with the given information. for example, lets say if the user clicks on the element with the id “myMenuButton”. we can either: display the menu for a normal click OR display that element’s context menu for a right click.

	if (elem_id == "myMenuButton") {
		if (rightclick) {
			var c_menu = document.getElementById("cMenu")
			c_menu.style.display = "block";
		} else {
			var my_menu = document.getElementById("myMenu")
			my_menu.style.display = "block";
		}
	}

return false
finally we want the function to return a value of false to suppress whatever action the browser wants to take from the click action. this is a good way to disable the browsers built in context menu

	return false;
}

the whole function

function eHandler() {

	// get the event
	if (!e) var e = window.event;

	// cross browser method to get the element that was clicked on
	if (e.target) elem = e.target;
	else if (e.srcElement) elem = e.srcElement;

	// get the element's id
	var elem_id = elem.getAttribute("id");

	// catch right clicks, rightclick is a boolean
	if (e.which) rightclick = (e.which == 3); // old netscape way
	else if (e.button) rightclick = (e.button == 2); // modern way

	if (elem_id == "myMenuButton") {
			var c_menu = document.getElementById("cMenu")
			c_menu.style.display = "block";
		} else {
			var my_menu = document.getElementById("myMenu")
			my_menu.style.display = "block";
		}
	}
	return false;

}

summation
its easy to see just how many possibilities event handlers really have when applied properly. combine this with some crafty AJAX and you’ve gone some serous web app potential at your fingertips.

Oct 10, 2008

document word replacement

while working on a contract recently i came across an issue that involved word replacement on pages throughout the site. the client wanted the ability to use a global variable that would represent the total number of subscribers to the site. that variable would then automatically be replaced be the actual number. however, the CMS that i constructed for the client involved a WYSIWYG editor (tinyMCE) and would not allow PHP to be inserted into the text. my solution was to combine php, mysql and javascript in a way that would replace a specific tag withing any page.

for the purpose of this example, let’s say all page content loads in a container div with the id=’container’ and that all text elements within that div are contained in ‘p’ tags. start out by writing a javascript function to replace all instances of the tag within the container p’s:

function globals(txt) {

	var page = document.getElementById("container");
	var p = page.getElementsByTagName("p");

	for(var i = 0; i < p.length; i++( {
		var x = p[i].innerHTML;
		if (x.indexOf('[subscribers]' >= 0) {
			x = p[i].innerHTML.replace("[subscribers]",txt);
			p[i].innerHTML = x;
		}
	}

}

then bring in the data from a table containing the global vars:

<?php
$sql = "SELECT * FROM globals_table WHERE ref_name='subscribers'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
?>

finally add a call to the function at the bottom of the page:
(here i combine javascript with shorthand php)

<script type="text/javascript">
<!--
globals('<?=number_format($globals['subscribers'])?>');
// -->
</script>

thats it! now whenever a pages loads, the global ‘subscribers’ value is brought in from the database. and send to a javascript function (via php) that will loop through all <p> tags inside the container div and replace any instance of “[subscribers]” with the actual number

Pages:«12