Page 1 of 1

AJAX Javascript Help Requested

Posted: Thu Jun 08, 2006 11:33 pm
by Benjamin
Hello,

I'm developing an AJAX application but I'm not big on Javascript. All the examples I have seen seem to be rather poorly coded. What I would like to make is an XML parser in Javascript to parse the response.

Here is an example.

Code: Select all

<?xml version="1.0">
<data>
	<data1>Name</data1>
	<data2>Fruit</data2>
	<data3>Vegetable</data3>
	<data4>Captain</data4>
</data>
What I would like to do with this is have the Javascript parse this and loop through all the tags inside the data tag. It would then update the corresponding div on the web page.

Code: Select all

<div id="data1"></div>
  <div id="data2"></div>
  <div id="data3"></div>
  <div id="data4"></div>
If the div tag doesn't exist, it should just skip it. I haven't found any code that can do this and I don't know how to write it. What I do have is below, but it only works for one field..

Code: Select all

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];
        }
    }
}
I think what I need is a modified version of this...

Code: Select all

/* Reference the product_list element to the variable product_list */
product_list = XMLReponse.getElementByTagName('product_id');

/* By substituting product_list for XMLResponse, we will be searching
	only the product_list element, not the entire response 
	We also use getElementsByTagName, not getElementByTagName, 
	since we are interested in all of the results, not just one. */

product_id = XMLResponse.getElementsByTagName('product');

/* getElementsByTagName produces an array, which we can access  like this:
	product_id[n], the same way we access an array item in PHP. 
	Let's get the id attribute from the product elements like this: */

for(i=0; i<product_id.length; i++){ //length is the same as count($array)
	id = product_id[i].getAttribute('id') //Grabs the id attribute.
	/* To get the text from within a text node, we use firstChild.data
		for the corresponding element. */
	name = product_id[i].getElementByTagName('name').firstChild.data;
	version = product_id[i].getElementByTagName('version').firstChild.data;
}
Can someone please help me?

Posted: Fri Jun 09, 2006 9:58 am
by pickle
Do you need help with the xmlhttp part or the xml parsing part? You could get the file you're calling (I'm assuming its a PHP file) to parse the XML & create the xhtml for you - then you don't need to worry about using Javascript to parse it.

Posted: Fri Jun 09, 2006 12:18 pm
by Benjamin
I just needed help getting the javascript to loop through a bunch of tags pulled from the server and automatically assign them to their corresponding containers on the web page. I figured it out though.